-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrixGenerateSpiral.cpp
More file actions
50 lines (37 loc) · 1.11 KB
/
Copy pathmatrixGenerateSpiral.cpp
File metadata and controls
50 lines (37 loc) · 1.11 KB
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
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> generateMatrix(int n, int m) {
int left = m-1, right = 0, top = 0, bottom = n-1;
vector<vector<int>> mat(n, vector<int> (m));
int val = 1;
while(right <= left || top <= bottom){
if(top <= bottom){
for(int i=right; i<=left; i++) mat[top][i] = val++;
top++;
}
if(right <= left){
for(int i=top; i<= bottom; i++) mat[i][left] = val++;
left--;
}
if(top <= bottom){
for(int i=left; i>= right; i--) mat[bottom][i] = val++;
bottom--;
}
if(right <= left){
for(int i=bottom; i >= top; i--) mat[i][right] = val++;
right++;
}
}
return mat;
}
};
int main(){
Solution s;
vector<vector<int>> mat = s.generateMatrix(5,5);
for(auto &v: mat){
for(auto &i: v) cout<<i<<"\t";
cout<<endl;
}
}