-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spriral_Matrix.cpp
42 lines (35 loc) · 1.17 KB
/
Spriral_Matrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty()) return {}; // Edge case
int rows = matrix.size();
int cols = matrix[0].size();
vector<int> ans(rows * cols);
int index = 0, i = 0, j = 0;
int rightBorder = cols - 1, leftBorder = 0;
int downBorder = rows - 1, upBorder = 0;
while (index < rows * cols) {
// Move right
while (j <= rightBorder && index < rows * cols) {
ans[index++] = matrix[i][j++];
}
j--; i++; upBorder++;
// Move down
while (i <= downBorder && index < rows * cols) {
ans[index++] = matrix[i++][j];
}
i--; j--; rightBorder--;
// Move left
while (j >= leftBorder && index < rows * cols) {
ans[index++] = matrix[i][j--];
}
j++; i--; downBorder--;
// Move up
while (i >= upBorder && index < rows * cols) {
ans[index++] = matrix[i--][j];
}
i++; j++; leftBorder++;
}
return ans;
}
};