看啥推荐读物
专栏名称: 眼若繁星丶
即使看清这个世界真实的样子,仍喜爱它
今天看啥  ›  专栏  ›  眼若繁星丶

模拟 02

眼若繁星丶  · 简书  ·  · 2021-03-15 10:15

模拟 02


54. 螺旋矩阵.png

模拟即可

  • 判断下一个左边边界是否溢出和是否遍历过,来决定是否改变方向
class Solution {

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<Integer>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }
        int rows = matrix.length, cols = matrix[0].length, totalElements = rows * cols;
        final int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        boolean visited[][] = new boolean[rows][cols];
        int x = 0, y = 0;
        int dirIdx = 0;     // 0 ~ 3: turning right / down / left / up
        for (int i = 0; i < totalElements; i++) {
            res.add(matrix[x][y]);
            visited[x][y] = true;
            int nextX = x + dir[dirIdx][0], nextY = y + dir[dirIdx][1];
            if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols || visited[nextX][nextY]) {
                dirIdx = (dirIdx + 1) % 4; // turning direction
            }
            x += dir[dirIdx][0];
            y += dir[dirIdx][1];
        }
        return res;
    }

}



原文地址:访问原文地址
快照地址: 访问文章快照