-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path59.spiral-matrix-ii.cpp
45 lines (39 loc) · 952 Bytes
/
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
/*
* @lc app=leetcode id=59 lang=cpp
*
* [59] Spiral Matrix II
*/
// @lc code=start
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <stack>
#include <unordered_map>
#include <utility>
#include <vector>
using namespace std;
#define DEBUG
class Solution {
public:
int floorMod(int x, int n) {
return ((x % n) + n) % n;
}
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> result (n, vector<int>(n));
const int dir[][2] = {{ 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 }};
int cnt = 1;
int x = 0;
int y = 0;
int d = 0;
while (cnt <= n * n) {
result[y][x] = cnt++;
int nx = floorMod(x + dir[d][1], n);
int ny = floorMod(y + dir[d][0], n);
if (result[ny][nx] != 0) d = (d + 1) % 4;
x += dir[d][1];
y += dir[d][0];
}
return result;
}
};
// @lc code=end