-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiralMatrix.cpp
88 lines (82 loc) · 1.99 KB
/
SpiralMatrix.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
#include<string>
#include <set>
#include<iostream>
#include<map>
#include<unordered_map>
#include<algorithm>
#include<stack>
#include<unordered_set>
#include <iterator>
#include<vector>
using namespace std;
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size(), n = m ? matrix[0].size() : 0, u = 0, d = m - 1, l = 0, r = n - 1, p = 0;
vector<int> order(m * n);
while (u <= d && l <= r) {
for (int col = l; col <= r; col++) {
order[p++] = matrix[u][col];
}
if (++u > d) {
break;
}
for (int row = u; row <= d; row++) {
order[p++] = matrix[row][r];
}
if (--r < l) {
break;
}
for (int col = r; col >= l; col--) {
order[p++] = matrix[d][col];
}
if (--d < u) {
break;
}
for (int row = d; row >= u; row--) {
order[p++] = matrix[row][l];
}
if (l++ > r) {
break;
}
}
return order;
}
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n, 0));
int u = 0, l = 0;
int d = n-1, r = n-1;
int count = 1;
while (u <= d && l <= r) {
for (int col = l; col <= r; col++) {
matrix[u][col] = count++;
}
if (++u > d) {
break;
}
for (int row = u; row <= d; row++) {
matrix[row][r] = count++;
}
if (--r < l) {
break;
}
for (int col = r; col >= l; col--) {
matrix[d][col] = count++;
}
if (--d < u) {
break;
}
for (int row = d; row >= u; row--) {
matrix[row][l] = count++;
}
if (l++ > r) {
break;
}
}
return matrix;
}
int main345()
{
vector<vector<int>> vec = { { 1, 2, 3 }, {4, 5, 6}, {7, 8, 9} };
//vector<int> r = spiralOrder(vec);
vector<vector<int>> vec1 = generateMatrix(3);
return 0;
}