forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spiral_Matrix.cpp
94 lines (76 loc) · 2.08 KB
/
Spiral_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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class Spiral_Matrix {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> arrLL;
//EDGE CASE
if (matrix.size() == 0) return arrLL;
int rows = matrix.size() ;
int columns = matrix[0].size() ;
if (rows == 1 && columns == 1) {
arrLL.push_back(matrix[0][0]);
return arrLL;
}
if (rows == 1) {
for (int j = 0; j < columns; j++){
arrLL.push_back(matrix[0][j]);
}
return arrLL;
}
if (columns == 1){
for (int i = 0; i < rows; i++){
arrLL.push_back(matrix[i][0]);
}
return arrLL;
}
int i, j, k1, k2, itr = 0;
while (j < columns || i < rows || j > k1 || i > k2){
bool cond1 = false;
while (j < columns ){
if (i != itr || i >= rows) break;
arrLL.push_back(matrix[i][j]);
j++;
cond1 = true;
}
i++; j--; n--;
bool cond2 = false;
while (i < rows && cond1 == true){
arrLL.push_back(matrix[i][j]);
cond2 = true;
i++;
}
j--; i--; m--;
bool cond3 = false;
while ( j>= k1 && cond2 == true){
arrLL.push_back(matrix[i][j]);
j--;
cond3 = true;
}
j++; i--; k1++;
while ( i > k2 && cond3 == true) {
arrLL.push_back(matrix[i][j]);
i--;
}
j++; i++; k2++;
itr ++;
}
return arrLL;
}
};
/*
TEST CASE
TIME COMPLEXITY : 0(N*M)
SPACE COMPLEXITY: 0(N+M)
where N is number of rows and M is number of columns
INPUT
[[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]]
OUTPUT
[1,2,3,6,9,8,7,4,5]
INPUT
[[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]]
OUTPUT
[1,2,3,4,8,12,11,10,9,5,6,7]
*/