Leetcode 885 螺旋矩阵 III ( Spiral Matrix III *Medium* ) 题解分析

题目介绍

You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.

You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid’s boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.

Return an array of coordinates representing the positions of the grid in the order you visited them.

Example 1:

Input: rows = 1, cols = 4, rStart = 0, cStart = 0
Output: [[0,0],[0,1],[0,2],[0,3]]

Example 2:

Input: rows = 5, cols = 6, rStart = 1, cStart = 4
Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]

Constraints:

  • 1 <= rows, cols <= 100
  • 0 <= rStart < rows
  • 0 <= cStart < cols

简析

这个题主要是要相同螺旋矩阵的转变方向的边界判断,已经相同步长会行进两次这个规律,写代码倒不复杂

代码

public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
        int size = rows * cols;
        int x = rStart, y = cStart;
        // 返回的二维矩阵
        int[][] matrix = new int[size][2];
        // 传入的参数就是入口第一个
        matrix[0][0] = rStart;
        matrix[0][1] = cStart;
        // 作为数量
        int z = 1;
        // 步进,1,1,2,2,3,3,4 ... 螺旋矩阵的增长
        int a = 1;
        // 方向 1 表示右,2 表示下,3 表示左,4 表示上
        int dir = 1;
        while (z < size) {
            for (int i = 0; i < 2; i++) {
                for (int j= 0; j < a; j++) {
                    // 处理方向
                    if (dir % 4 == 1) {
                        y++;
                    } else if (dir % 4 == 2) {
                        x++;
                    } else if (dir % 4 == 3) {
                        y--;
                    } else {
                        x--;
                    }
                    // 如果在实际矩阵内
                    if (x < rows && y < cols && x >= 0 && y >= 0) {
                        matrix[z][0] = x;
                        matrix[z][1] = y;
                        z++;
                    }
                }
                // 转变方向
                dir++;
            }
            // 步进++
            a++;
        }
        return matrix;
    }

结果