-
Notifications
You must be signed in to change notification settings - Fork 0
/
59.spiral_matrix_II.cpp
52 lines (47 loc) · 1.35 KB
/
59.spiral_matrix_II.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
//coding:utf-8
/*****************************************
Program: spiral matrix II
Description:
Author: [email protected]
Date: 2016-08-29 16:08:51
Last modified: 2016-08-29 16:23:35
GCC version: 4.9.3
*****************************************/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<pair<int, int>> dir{make_pair(0, 1), make_pair(1, 0), make_pair(0, -1), make_pair(-1, 0)};
vector<vector<int>> ret(n, vector<int>(n, 0));
int idx = 0;
int i = 0, j = 0, val = 1, sq = n * n;
while(val <= sq) {
if(i >= 0 && i < n && j >= 0 && j < n && ret[i][j] == 0) {
ret[i][j] = val++;
i += dir[idx % 4].first;
j += dir[idx % 4].second;
}
if(!(i >= 0 && i < n && j >= 0 && j < n && ret[i][j] == 0)) {
i -= dir[idx % 4].first;
j -= dir[idx % 4].second;
idx++;
i += dir[idx % 4].first;
j += dir[idx % 4].second;
}
}
return ret;
}
};
void print(vector<vector<int>> maxtrix) {
for(auto vec: maxtrix) {
for(auto d: vec)
cout << d << " ";
cout << endl;
}
}
int main() {
Solution s;
print(s.generateMatrix(5));
}