[Math_Medium] 885. Spiral Matrix III

原题:885. Spiral Matrix III

On a 2 dimensional grid with R rows and C columns, we start at (r0, c0) facing east.
Here, the north-west corner of the grid is at the first row and column, and the south-east corner of the grid is at the last row and column.
Now, we walk in a clockwise spiral shape to visit every position in this grid.
Whenever we would move outside the boundary of the grid, we continue our walk outside the grid (but may return to the grid boundary later.)
Eventually, we reach all R * C spaces of the grid.
Return a list of coordinates representing the positions of the grid in the order they were visited.

题目大意:

给定一个 R*C的矩阵,以及初始坐标(r0, c0), 你开始面向东,以顺时针方向做螺旋运动,当你走完所有的点后,要求记录你所走的轨迹,如下图所示
示例1:

Input: R = 1, C = 4, r0 = 0, c0 = 0
Output: [[0,0],[0,1],[0,2],[0,3]]

e.g. 1

示例2:

Input: R = 5, C = 6, r0 = 1, c0 = 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]]

e.g. 2

解题思路:

通过示例2的图我们可以观察到,我们是先往东走1步,再往南走一步,然后再往西走2步,再往北走2步,之后再往东走3步,再往南走3步,可以看到其走的步数是 1,1,2,2,3,3,4,4,5,5,6,6.....;我们以一圈为一组,即往东南西北四个方向都走一遍为1组,即1,1,2,2 |,3,3,4,4 |,5,5,6,6|.....;
往东走对应坐标变化:(0, +1)
往南走对应坐标变化:(+1, 0)
往西走对应坐标变化:(0, -1)
往北走对应坐标变化:(-1, 0)
因此可以:dx = {0, 1, 0, -1}; dy = {1, 0, -1, 0};
然后每一组逐一遍历往哪个方向(r0 + dx[i], c0 + dy[i])走几步即可

代码如下:

class Solution {
public:
    vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) 
    {
        vector<vector<int> > ans = {{r0, c0}};
        int dx[4] = {0, 1, 0, -1};
        int dy[4] = {1, 0, -1, 0};
        int dk = 1;
        for(int i = 1; i < 2 * R * C; i += 2)
        {
            for(int j = 0; j < 4; j++)
            {
                dk = i + j / 2;
                for(int k = 0; k < dk; k++)
                {
                    r0 += dx[j];
                    c0 += dy[j];
                    if(r0 >= 0 && r0 < R && c0 >= 0 && c0 < C)
                        ans.push_back({r0,c0});
                    if(ans.size() == R*C)
                        return ans;
                }
            }
        }
    }
};

代码2:

class Solution {
public:
    vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) 
    {
        vector<vector<int> > ans = {{r0, c0}};
        int dx[4] = {0, 1, 0, -1};
        int dy[4] = {1, 0, -1, 0};
        int num=0, steps=1;
        while(ans.size() < R * C)
        {
            for(int i = 0; i < 4; i++)
            {
                for(int j = 0; j < steps; j++)
                {
                    r0 += dx[i];
                    c0 += dy[i];
                    if(r0 >= 0 && r0 < R && c0 >= 0 && c0 < C)
                        ans.push_back({r0, c0});
                }
                num++;
                if(num%2==0)
                    steps++;
            }
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/qiulinzhang/p/9564454.html