看板 Marginalman
2024-08-08 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. 好像只能照著刻然後一格一格走塞進去欸? 在外面的時候可能可以用數學解跳過吧 可是感覺好麻煩 基本上蘿懸是從最小圈開始往前走一格以後轉彎 每轉彎兩次會碰到上一圈的 要多走一格 class Solution { public: vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) { const vector<vector<int>> ds = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; const int grids_number = rows * cols; vector<vector<int>> results; int max_step = 1; int dir = 0; int step = 0; int x = cStart, y = rStart; while (results.size() < grids_number) { if (isInside(x, y, rows, cols)) { results.push_back({y, x}); } x += ds[dir][0]; y += ds[dir][1]; step++; if (step == max_step) { step = 0; dir = (dir + 1) % 4; if (!(dir % 2)) { max_step++; } } } return results; } private: inline bool isInside(const int x, const int y, const int rows, const int cols) { return x >=0 && x < cols && y >= 0 && y < rows; } }; -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 73.173.211.221 (美國) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1723088075.A.2B6.html
oin1104: 大師 08/08 11:35