Loading

LeetCode 54 螺旋矩阵

LeetCode54 螺旋矩阵

题目描述

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

样例

输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

算法分析

模拟方法

int[] dx = {0, 1, 0, -1};
int[] dy = {1, 0, -1, 0};
//   右  下  左   上   方向的顺序

//改变方向  d+=1 d%4

时间复杂度

$ O(nm) $

Java代码

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int n = matrix.length;
        if (n == 0) {
            return res;
        }
        int m = matrix[0].length;
        boolean[][] st = new boolean[n][m];
        int[] dx = {0, 1, 0, -1};
        int[] dy = {1, 0, -1, 0};
        for (int x = 0, y = 0, d = 0, i = 0; i < n * m; i++) {
            st[x][y] = true;
            res.add(matrix[x][y]);
            x += dx[d];
            y += dy[d];
            if (x < 0 || x >= n || y < 0 || y >= m || st[x][y]) {
                x -= dx[d];
                y -= dy[d];  //先减去之前加上的值
                d = (d + 1) % 4;   // 改变方向
                x += dx[d];
                y += dy[d];
            }
        }
        return res;
    }
}
posted @ 2020-11-11 16:30  想用包子换论文  阅读(104)  评论(0)    收藏  举报