LeetCode: Spiral Matrix  解题报告

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].

Solution 1:

使用递归,一次扫描一整圈,然后用x,y记录这个圈的左上角,递归完了都+1。rows, cols记录还没扫的有多少。思想比较简单,但相当容易出错。起码提交了5次才最后过。

注意:1. 扫描第一行跟最后一行要扫到底部为止,而扫描左列和右列只需要扫中间的。

1  2  3   4

5  6  7   8

9 10 11 12

例如以上例子: 你要 先扫1234, 然后是8,然后是12 11 10 9 然后是 5.

不能这样:123, 4 8, 12 11 10 , 9 5。 用后者的方法在只有一个数字 1的时候 就完全不会扫到它。

 

 1 public List<Integer> spiralOrder1(int[][] matrix) {
 2         List<Integer> ret = new ArrayList<Integer>();
 3         if (matrix == null || matrix.length == 0 
 4             || matrix[0].length == 0) {
 5             return ret;   
 6         }
 7         
 8         rec(matrix, 0, 0, matrix.length, matrix[0].length, ret);
 9         
10         return ret;
11     }
12     
13     public static void rec(int[][] matrix, int x, int y, int rows, int cols, List<Integer> ret) {
14         if (rows <= 0 || cols <= 0) {
15             return;
16         }
17         
18         // first line
19         for (int i = 0; i < cols; i++) {
20             ret.add(matrix[x][y + i]);
21         }
22         
23         // right column
24         for (int i = 1; i < rows - 1; i++) {
25             ret.add(matrix[x + i][y + cols - 1]);
26         }
27         
28         // down row
29         if (rows > 1) {
30             for (int i = cols - 1; i >= 0; i--) {
31                 ret.add(matrix[x + rows - 1][y + i]);
32             }    
33         }
34         
35         // left column. GO UP.
36         if (cols > 1) {
37             for (int i = rows - 2; i > 0; i--) {
38                 ret.add(matrix[x + i][y]);
39             }    
40         }
41         
42         rec (matrix, x + 1, y + 1, rows - 2, cols - 2, ret);
43     }
View Code

相关文章:

  • 2021-09-01
  • 2022-03-04
  • 2021-09-15
  • 2022-12-23
  • 2022-12-23
  • 2022-02-23
  • 2021-10-07
  • 2021-06-02
猜你喜欢
  • 2021-12-17
  • 2021-12-01
  • 2022-12-23
  • 2022-02-26
  • 2022-03-02
  • 2021-11-07
相关资源
相似解决方案