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

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
 
题意:螺旋矩阵,按螺旋的方式打印
有的题也叫蛇形矩阵,题本身不难,就是遍历,和越界问题。
主要考验的是耐心和细心
class Solution {
    public List spiralOrder(int[][] matrix) {
        int n = matrix.length;
        if (n == 0)
            return new ArrayList<>();
        int m = matrix[0].length;
        if (m == 0)
            return new ArrayList<>();
        List res = new ArrayList<>(m * n);
        int k = 0;
        int i = 0;
        int j = 0;
        boolean left = true;
        boolean down = false;
        boolean up = false;
        boolean right = false;
        int sum = m * n;
        int upn = -1;
        int upm = -1;
        while (k <sum) {
            res.add(matrix[i][j]);
            k ++;
            if (left) {
                j ++;
                if (j == m) {
                    j --;
                    i ++;
                    left = !left;
                    down = !down;
                    upn ++;
                }
            } else if (down) {
                i ++;
                if (i == n) {
                    i --;
                    j --;
                    down = !down;
                    right = !right;
                    m --;
                }
            } else if (right) {
                j --;
                if (j == upm) {
                    j ++;
                    i --;
                    right = !right;
                    up = !up;
                    n --;
                }
            } else if (up) {
                i --;
                if (i == upn) {
                    i++;
                    j++;
                    up = !up;
                    left = !left;
                    upm ++;
                }
            }
        }
        return res;
    }
}

 

转载于:https://www.cnblogs.com/Moriarty-cx/p/9943203.html

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