1
class Solution {
2
public:
3
vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
4
vector<vector<int>> ans;
5
ans.push_back({rStart, cStart}); // Pushing the starting point in answer
6
int topRow = rStart - 1; // Row above starting point
7
int bottomRow = rStart + 1; // Row below starting point
8
int leftCol = cStart - 1; // Col left to starting point
9
int rightCol = cStart + 1; // Col right to starting point
10

11
while (topRow != -1 || bottomRow != rows || leftCol != -1 ||
12
rightCol != cols) { // Untill all rows and columns are exhausted
13

14
if (rightCol != cols) { // Checking if this col is exhausted
15
for (int i = topRow + 1; i < bottomRow; i++)
16
ans.push_back({i, rightCol}); // Running loop from one bottom of top
17
// row till bottom row in right col
18
rightCol++; // Incrementing the col forward
19
}
20
// Similar things are done below with different cols and rows
21
if (bottomRow != rows) {
22
for (int j = rightCol - 1; j > leftCol; j--) ans.push_back({bottomRow, j});
23
bottomRow++;
24
}
25

26
if (leftCol != -1) {
27
for (int i = bottomRow - 1; i > topRow; i--) ans.push_back({i, leftCol});
28
leftCol--;
29
}
30

31
if (topRow != -1) {
32
for (int j = leftCol + 1; j < rightCol; j++) ans.push_back({topRow, j});
33
topRow--;
34
}
35
}
36
return ans;
37
}
38
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0