54. Spiral Matrix (Matrix)
设置toprow bottomrow leftcol rightcol来标记边界,然后对每一条边界进行循环 要是list的size等于matrix的size的话 就表明结束了
1 class Solution { 2 public List<Integer> spiralOrder(int[][] matrix) { 3 List<Integer> res = new ArrayList<>(); 4 if(matrix == null || matrix.length == 0 || matrix[0].length == 0) { 5 return res; 6 } 7 int row = matrix.length; 8 int col = matrix[0].length; 9 int n = row * col; 10 int toprow = 0; 11 int bottomrow = row - 1; 12 int leftcol = 0; 13 int rightcol = col - 1; 14 15 while(res.size() < n) { 16 for(int i = leftcol; i <= rightcol; i++) { 17 res.add(matrix[toprow][i]); 18 } 19 if(res.size() == n) break; 20 toprow++; 21 22 for(int i = toprow; i <= bottomrow; i++) { 23 res.add(matrix[i][rightcol]); 24 } 25 if(res.size() == n) break; 26 rightcol--; 27 28 for(int i = rightcol; i >= leftcol; i--) { 29 res.add(matrix[bottomrow][i]); 30 } 31 if(res.size() == n) break; 32 bottomrow--; 33 34 for(int i = bottomrow; i >= toprow; i--) { 35 res.add(matrix[i][leftcol]); 36 } 37 if(res.size() == n) break; 38 leftcol++; 39 40 } 41 return res; 42 43 } 44 }