LeetCode 54. Spiral Matrix

原题链接在这里: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.

r1 = 0, r2 = m - 1, c1 = 0, c2 = n - 1 as boundary.

while loop condition r1 <= r2, and c1 <= c2. As this fullfills, we need to fill the value to res.

When there is only one row or one column left, we only need first 2 for loops. To check this, use r1 < r2 && c1 < c2. 

As when r1 == r2 || c1 == c2, there is only one row or one column left.

Note, the last for loop stop condition is r > r1, not r >= r1 since r == r1 has been covered by the first loop.

Time Complexity: O(m*n).

Space: O(1), regardless res.

AC Java:

 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         
 8         int m = matrix.length;
 9         int n = matrix[0].length;
10         int r1 = 0, c1= 0;
11         int r2 = m - 1, c2 = n - 1;
12         while(r1 <= r2 && c1 <= c2){
13             for(int c = c1; c <= c2; c++){
14                 res.add(matrix[r1][c]);
15             }
16             
17             for(int r = r1 + 1; r <= r2; r++){
18                 res.add(matrix[r][c2]);
19             }
20             
21             if(r1 < r2 && c1 < c2){
22                 for(int c = c2 - 1; c >= c1; c--){
23                     res.add(matrix[r2][c]);
24                 }
25                 
26                 for(int r = r2 -1; r > r1; r--){
27                     res.add(matrix[r][c1]);
28                 }
29             }
30             
31             r1++;
32             r2--;
33             c1++;
34             c2--;
35         }
36         
37         return res;
38     }
39 }

跟上Spiral Matrix IISpiral Matrix IIISpiral Matrix IV.

类似Diagonal Traverse.

posted @ 2015-09-26 03:00  Dylan_Java_NYC  阅读(349)  评论(0编辑  收藏  举报