题目
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.
Example 1:
Input: R = 1, C = 4, r0 = 0, c0 = 0
Output: [[0,0],[0,1],[0,2],[0,3]]
Example 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]]
解析
这道题其实很简单,按照它说的规则来就好了;点从(r0, c0)位置出发,以方向为右——>——>下——>左——>上的绕圈走法,而我们需要去记录这种走法所经过的二维表的格子位置,仔细观察这种走法,可以发现这种规律
向右走与向左走
点首先从(r0, c0)出发向右走一格,当他要向左走时,向左走的格数是上一次向右走的格子数加上一,同理,向右走的格子数是上一次向左走的格子数加一
向上走与向下走
向上走与向下走的规律和上面的规律一样
规律分析清楚了,那么,怎么实现呢?可以设置一个长度为5的int类型的数组direction
,数组内部存储的数据如下
1 | direction = [0, 1, 2, -1, -2] (1 代1表向右走,2 代表向下走,-1 代表向左走,-2 代表向上走) |
同时,设置一个方向标记index
,记录行走的方向,当index为4时,代表此时点已经以向上的方向走完了相应的格子数,这时,又重新回到了右——>——>下——>左——>上的绕圈走法
,因此将index置为0,待index自增后重新开始指向向右走的方向
解题代码
1 | class Solution: |