LeetCode之54. 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].

题目大意

给一个矩阵,按照螺旋顺序返回矩阵的所有元素。

算法分析

按照从→ ↓ ←↑循环遍历整个矩阵。

代码如下
  • Java
public List spiralOrder(int[][] matrix) {
        List resultList = new ArrayList<>();
        if (matrix.length == 0)
            return resultList;
        int left = 0;
        int right = matrix[0].length-1;
        int up = 0;
        int down = matrix.length-1;
        while (left<=right && up<=down) {
            for (int j=left; j<=right; j++) {
                resultList.add(matrix[up][j]);
            }
            up++;

            for (int j=up; j<=down; j++) {
                resultList.add(matrix[j][right]);
            }
            right--;

            if (up<=down) {
                for (int j=right;j>=left;j--) {
                    resultList.add(matrix[down][j]);
                }
            }
            down--;

            if (left<=right) {
                for (int j=down;j>=up;j--) {
                    resultList.add(matrix[j][left]);
                }
            }
            left++;
        }
        return resultList;
    }

你可能感兴趣的:(LeetCode之54. Spiral Matrix)