Spiral Matrix(I II III)螺旋矩阵一、二、三(leetcode54、59、885)
好久没写算法,这种找规律的反应不过来了,还卡了我好久这里就写下三的做法。
885. Spiral Matrix III
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.
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]] 其实刚开始看的时候感觉有规律,手画了一遍,就是没找出来。最后运来发现是我把开始点也算做1距离了,就没看出来。 这题的规律就是一开始向右,然后转一次向就距离加一。
class Solution { public int[][] spiralMatrixIII(int rows, int cols, int r0, int c0) { int[][] dir = new int[][]{{0,1},{1,0},{0,-1},{-1,0}}; ArrayList<int[]> res = new ArrayList<>(); int len =0,d=0; res.add(new int[]{r0,c0}); while(res.size()<rows*cols){ if(d==0||d==2) len++; for (int i = 0; i < len; i++) { r0 += dir[d][0]; c0+=dir[d][1]; if(r0>=0&&r0<rows&&c0>=0&&c0<cols){ res.add(new int[]{r0,c0}); } } d=(d+1)%4; } return res.toArray(new int[rows*cols][2]); } }
本文系作者 @rinbn 原创发布在 噓だ。未经许可,禁止转载。