Leetcode 54. Spiral Matrix

来源:互联网 发布:nginx tomcat 502 编辑:程序博客网 时间:2024/05/18 01:28

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

方法不管三七二十一地遍历一遍矩阵。

注意 corner cases

    public List<Integer> spiralOrder(int[][] matrix) {        List<Integer> res = new ArrayList<>();        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--;            // left            if (rowBegin <= rowEnd) {                for (int i = colEnd; i >= colBegin; i--) {                    res.add(matrix[rowEnd][i]);                }            }            rowEnd--;            // up            if (colBegin <= colEnd) {                for (int i = rowEnd; i >= rowBegin; i--) {                    res.add(matrix[i][colBegin]);                }            }            colBegin++;        }        return res;    }


0 0