885. Spiral Matrix III的C++解法
阿新 • • 發佈:2018-11-11
模擬轉圈即可。假設圖紙無限大(可以越界),只有真正落在給出的棋盤範圍的座標才被記錄下來。
轉圈有兩個規則:
1.步長從1開始,每走兩個方向則步長增加1;
2.每走完一個步長,方向換一個;
我用了一個引數d記錄走了多少步。d被2整除的時候說明要增加步長,接下來要走的方向是(d%4)。
速度打敗100%。
class Solution { public: vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) { vector<vector<int>> direct = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; vector<vector<int>> res; int count = 1; int step = 1; int d = 0; int s = 1; res.push_back({ r0, c0 }); while (count < R*C) { for (int i = 1; i <= step; i++) { int tmp = d % 4; r0 += direct[tmp][0]; c0 += direct[tmp][1]; if ((r0 < R) && (c0 < C) && (r0 >= 0) && (c0>= 0)) { res.push_back({r0, c0}); count++; if (count == R*C) break; } } d++; if (d % 2 == 0) step++; } return res; } };
相關題目:
54. Spiral Matrix的C++解法
59. Spiral Matrix II的C++解法