-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0059.cpp
More file actions
36 lines (28 loc) · 987 Bytes
/
Copy path0059.cpp
File metadata and controls
36 lines (28 loc) · 987 Bytes
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
class Solution {
pair<int, int> offset[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int limit_offset[4] = {1, -1, -1, 1};
int limit[4] = {0, 0, 0, 0};
int &m = limit[2], &n = limit[1];
bool valid(int i, int j) { return i >= limit[0] && i <= m && j >= limit[3] && j <= n; }
public:
vector<vector<int>> generateMatrix(int dim) {
vector<vector<int>> res(dim, vector<int>(dim));
int direction = 0;
int cnt = 0;
int size;
int i = 0, j = 0;
m = n = dim - 1;
size = (m + 1) * (n + 1);
while (true) {
res[i][j] = ++cnt;
if (cnt == size) break;
if (!valid(i + offset[direction].first, j + offset[direction].second)) {
limit[direction] += limit_offset[direction];
direction = (direction + 1) % 4;
}
i += offset[direction].first;
j += offset[direction].second;
}
return res;
}
};