力扣 54 螺旋矩阵 方向键 || 剑指 Offer 29. 顺时针打印矩阵

题目链接

**思路 : **使用方向键,或者模拟(模拟太容易出问题,建议使用方向键)。
代码

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return list;
        }
        
        int m = matrix.length;
        int n = matrix[0].length;

        int [][]vis = new int[m][n];

        int index = 1;
        // 右下左上
        int [][]dir = {
                {0, 1}, {1, 0}, {0, -1}, {-1, 0}
        };

        int si = 0, sj = 0;
        // 临时判断使用
        int fi = 0, fj = 0;
        list.add(matrix[0][0]);
        vis[0][0] = 1;
        int direction = 0;
        for (int i = 1; i < m * n; i++) {
            fi = si + dir[direction][0];
            fj = sj + dir[direction][1];

            // 不能一直往一个方向,就转向
            if (!(fi >= 0 && fi < m && fj >= 0 && fj < n && vis[fi][fj] == 0)) {
                direction = (direction + 1) % 4;
            }

            si += dir[direction][0];
            sj += dir[direction][1];
            list.add(matrix[si][sj]);
            vis[si][sj] = 1;
        }
        return list;
    }

代码

    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length < 1 || matrix[0].length < 1) return new int[0];

        int sum = matrix[0].length * matrix.length;

        int [][]vis = new int[matrix.length][matrix[0].length];

        int column = matrix[0].length, row = matrix.length;
        int []ans = new int[sum];

        int count = 1;

        // 表示右下左上方向
        int [][]dir = {
                {0, 1}, {1, 0}, {0, -1}, {-1, 0}
        };

        int si = 0, sj = 0;
        ans[0] = matrix[0][0];
        vis[0][0] = 1;
        while (count < sum) {
            for (int i = 0; i < 4; i++) {
                si += dir[i][0];
                sj += dir[i][1];

                //System.out.println("si: " + si + " sj : " + sj);
                // 表单方向一致前进
                while (si >= 0 && si < row && sj >= 0 && sj < column && vis[si][sj] == 0) {
                    vis[si][sj] = 1;

                    //System.out.print(matrix[si][sj] + " ");
                    ans[count++] = matrix[si][sj];

                    si += dir[i][0];
                    sj += dir[i][1];
                }

                //System.out.println();

                // 此时需要回退
                si -= dir[i][0];
                sj -= dir[i][1];
            }
        }

        return ans;
    }
posted @ 2020-08-22 09:00  Bears9  阅读(103)  评论(0编辑  收藏  举报