Skip to content

54. Spiral Matrix

Jacky Zhang edited this page Nov 1, 2016 · 2 revisions

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

解题思路straightforward。 按照right->down->left->up的顺序扫描matrix,并update四个边界。 注意的是在left和up之前需要check是否有有效的行或列。

left时不检查的话,

[1,2] 输出[1,2,1]

up时不检查的话

[[1],[2],[3]] 输出[1,2,3,2]
public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<Integer>();
        if(matrix == null || matrix.length == 0) return res;
        int rowBegin = 0;
        int rowEnd = matrix.length - 1;
        int colBegin = 0;
        int colEnd = matrix[0].length - 1;
        while(rowBegin <= rowEnd && colBegin <= colEnd) {
            // right
            for(int i = colBegin; i <= colEnd; i++) {
                res.add(matrix[rowBegin][i]);
            }
            rowBegin++;
            // down
            for(int i = rowBegin; i <= rowEnd; i++) {
                res.add(matrix[i][colEnd]);
            }
            colEnd--;
            if(rowBegin > rowEnd) break;
            // left
            for(int i = colEnd; i >= colBegin; i--) {
                res.add(matrix[rowEnd][i]);
            }
            rowEnd--;
            if(colBegin > colEnd) break;
            // up
            for(int i = rowEnd; i >= rowBegin; i--) {
                res.add(matrix[i][colBegin]);
            }
            colBegin++;
        }
        return res;
    }
}
Clone this wiki locally