54. Spiral Matrix I & II

Spiral Matrix I

Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

Example

Given n = 3,

You should return the following matrix:

[
  [ 1, 2, 3 ],
  [ 8, 9, 4 ],
  [ 7, 6, 5 ]
]

分析:
从上,右,下,左打印。
 1 public class Solution {
 6     public int[][] generateMatrix(int n) {
 7         
 8         int[][] arr = new int[n][n];
 9         int a = 0;
10         int b = n - 1;
11         int k = 1;
12         
13         while (a < b) {
14             for (int i = a; i <= b; i++) {
15                 arr[a][i] = k++;
16             }
17             
18             for (int i = a + 1 ; i <= b - 1; i++) {
19                 arr[i][b] = k++;
20             }
21             
22             for (int i = b ; i >= a; i--) {
23                 arr[b][i] = k++;
24             }
25             
26             for (int i = b - 1 ; i >= a + 1; i--) {
27                 arr[i][a] = k++;
28             }
29             
30             a++;
31             b--;
32         }
33         // if n is odd, it will be executed, if it is even, it won't be executed.
34         if (a == b) {
35             arr[a][b] = k; 
36         }
37         return arr;
38     }
39 }

 

Spiral Matrix II

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

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

分析:

拿到左上角和右下角的坐标,然后从上,右,下,左打印。然后更新坐标。

 1 public class Solution {
 2     public List<Integer> spiralOrder(int[][] matrix) {
 3         List<Integer> list = new ArrayList<>();
 4         
 5         if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return list;
 6         int a = 0, b = 0;
 7         int x = matrix.length - 1, y = matrix[0].length - 1;
 8         
 9         while (a <= x && b <= y) {
10             // top row
11             for (int i = b; i <= y; i++) {
12                 list.add(matrix[a][i]);
13             }
14             // right column
15             for (int i = a + 1; i <= x - 1; i++) {
16                 list.add(matrix[i][y]);
17             }
18             // bottom row
19             if (a != x) {
20                 for (int i = y; i >= b; i--) {
21                     list.add(matrix[x][i]);
22                 }
23             }
24             // left column
25             if (b != y) {
26                 for (int i = x - 1; i >= a + 1; i--) {
27                     list.add(matrix[i][b]);
28                 }
29             }
30             
31             a++;
32             b++;
33             x--;
34             y--;
35         }
36         return list;
37     }
38 }

 

posted @ 2016-07-18 11:44  北叶青藤  阅读(208)  评论(0)    收藏  举报