0054. Spiral Matrix

54. Spiral Matrix #

题目 #

给定一个mn列的矩阵matrix,按照顺时针螺旋顺序,返回矩阵中的所有元素。

思路 #

代码 #

class Solution {
    public void circle(int[][] matrix, List<Integer> result, int top, int left, int right, int bottom) {
        if (top > bottom || left > right) return;
        if (top == bottom) { for (int j=left; j<=right; j++) result.add(matrix[top][j]); return; }
        else if (left == right) { for (int i=top; i<=bottom; i++) result.add(matrix[i][left]); return; }
        for (int j=left; j<right; j++) result.add(matrix[top][j]);
        for (int i=top; i<bottom; i++) result.add(matrix[i][right]);
        for (int j=right; j>left; j--) result.add(matrix[bottom][j]);
        for (int i=bottom; i>top; i--) result.add(matrix[i][left]);
        circle(matrix, result, top+1, left+1, right-1, bottom-1);
    }
    public List<Integer> spiralOrder(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        List<Integer> result = new ArrayList<Integer>();
        circle(matrix, result, 0, 0, n-1, m-1);
        return result;
    }
}

致谢 #