LeetCode 54. Spiral Matrix(螺旋矩陣)
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
題目標簽:Array
這道題目給了我們一個矩陣,m*n,讓我們返回一個螺旋矩陣排列的array,這題目名字聽著挺酷炫呀。我們來看原題例子:
1 2 3
4 5 6
7 8 9
一共有4步驟:我們還需要設置rowBegin = 0, rowEnd = 2, colBegin = 0, colEnd = 2.
1. 紅色:從rowBegin這一排向右遍歷,加入每一個matrix[rowBegin][j], j: colBegin ~ colEnd. 遍歷完要把rowBegin++, 從下一排繼續;
2. 綠色:從colEnd這一列開始向下遍歷,加入每一個matrix[j][colEnd], j: rowBegin ~ rowEnd. 遍歷完要把colEnd--, 從左邊那列繼續;
3. 藍色:從rowEnd這一排向左遍歷,加入每一個matrix[rowEnd][j], j: colEnd ~ colBegin. 遍歷完要把rowEnd--, 從上一排繼續。
4. 灰色:從colBegin這一列開始向上遍歷,加入每一個matrix[j][colBegin], j: rowEnd ~ rowBegin, 遍歷完要把colBegin++, 從右邊那列繼續。
那什麽時候要結束呢,可以利用m*n 得到一共的數量,每次加入一個,就把這個數量-1, 當數量等於0的時候意味著我們加完了所有的數字,return res 就可以了。
Java Solution:
Runtime beats 20.42%
完成日期:07/18/2017
關鍵詞:Array
關鍵點:螺旋矩陣的固定模式
1 public class Solution 2 { 3public List<Integer> spiralOrder(int[][] matrix) 4 { 5 List<Integer> res = new ArrayList<Integer>(); 6 7 if(matrix.length == 0) 8 return res; 9 10 int totalNum = matrix.length * matrix[0].length; 11 12 int rowBegin = 0; 13 int rowEnd = matrix.length - 1; 14 int colBegin = 0; 15 int colEnd = matrix[0].length - 1; 16 17 while(totalNum > 0) 18 { 19 // traverse right 20 for(int j=colBegin; j<=colEnd && totalNum>0; j++) 21 { 22 res.add(matrix[rowBegin][j]); 23 totalNum--; 24 } 25 rowBegin++; 26 27 // traverse Down 28 for(int j=rowBegin; j<=rowEnd && totalNum>0; j++) 29 { 30 res.add(matrix[j][colEnd]); 31 totalNum--; 32 } 33 colEnd--; 34 35 // traverse left 36 for(int j=colEnd; j>=colBegin && totalNum>0; j--) 37 { 38 res.add(matrix[rowEnd][j]); 39 totalNum--; 40 } 41 rowEnd--; 42 43 // traverse up 44 for(int j=rowEnd; j>= rowBegin && totalNum>0; j--) 45 { 46 res.add(matrix[j][colBegin]); 47 totalNum--; 48 } 49 colBegin++; 50 } 51 52 return res; 53 54 } 55 }
參考資料:
https://leetcode.com/problems/spiral-matrix/#/discuss
LeetCode 算法題目列表 - LeetCode Algorithms Questions List
LeetCode 54. Spiral Matrix(螺旋矩陣)