Untitled
class Solution { public: vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) { int idx = 0; int times = 1; vector<vector<int>> ans; int totalGrids = rows * cols; vector<int> pos = {rStart, cStart}; int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; ans.emplace_back(pos); while (ans.size() < totalGrids) { for (int i=0; i<times; ++i) { pos[0] += dir[idx % 4][0]; pos[1] += dir[idx % 4][1]; if (pos[0] >= rows || pos[1] >= cols || pos[0] < 0 || pos[1] < 0) continue; ans.emplace_back(pos); } idx ++; if (!(idx % 2)) times ++; } return ans; } };
Leave a Comment