原题链接在这里:https://leetcode.com/problems/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]
.
题解:
转圈取值. 矩阵size 是 m*n, 第一行取值,从matrix[0][0]到matrix[0][n-2], 留下一个值为了接下来取最后一列的开始点,以此类推。
注意当只有一行或者一列时,要全部取值不能留下最后一个。
x代表当前row, y代表当前column.
走完一圈相当于走过两行,两列,所以m-=2, n-=2.
Time Complexity: O(m*n). Space: O(m*n).
AC Java:
1 public class Solution { 2 public ListspiralOrder(int[][] matrix) { 3 List res = new ArrayList (); 4 if(matrix == null || matrix.length == 0 || matrix[0].length == 0){ 5 return res; 6 } 7 int m = matrix.length; 8 int n = matrix[0].length; 9 int x = 0; 10 int y = 0; 11 while(m > 0 && n > 0){ 12 if(m == 1){ //There is only one row 13 for(int j = 0; j ){ 14 res.add(matrix[x][y++]); 15 } 16 break; 17 } 18 if(n == 1){ //There is only one column 19 for(int i = 0; i ){ 20 res.add(matrix[x++][y]); 21 } 22 break; 23 } 24 25 //旋转扫描 26 //首先,左到右 27 for(int j = 0; j ){ 28 res.add(matrix[x][y++]); 29 } 30 //上到下 31 for(int i = 0; i ){ 32 res.add(matrix[x++][y]); 33 } 34 //右到左 35 for(int j = 0; j ){ 36 res.add(matrix[x][y--]); 37 } 38 //下到上 39 for(int i = 0; i ){ 40 res.add(matrix[x--][y]); 41 } 42 x++; 43 y++; 44 m -= 2; 45 n -= 2; 46 } 47 return res; 48 } 49 }
跟上Spiral Matrix II, Spiral Matrix III.
类似Diagonal Traverse.