source: https://leetcode.com/problems/spiral-matrix-ii/
C/C++ Solution to LeetCode problem 59. Spiral Matrix II.
Problem
Given a positive integer n
, generate an n x n
matrix
filled with elements from 1
to n2
in spiral order.
Examples
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints
1 <= n <= 20
Solution
Same solution that the one for problem 54, but instead of reading a value, we write a value.
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
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> result(n, vector<int>(n));
int dr = 0;
int dc = 1;
int r = 0;
int c = -1;
int minCol = -1;
int maxCR = n;
int minRow = 0;
for (int i=1; i<=(n*n); i++) {
r += dr;
c += dc;
result[r][c] = i;
if ((r == minRow && c == minCol) || (minCol == -1 && c==0)) {
maxCR--;
if (minCol < maxCR) {
dr = 0;
dc = 1;
}
} else if (r == maxCR && c == maxCR) {
minRow++;
minCol++;
dr = 0;
dc = -1;
continue;
}
if (r == maxCR && c == minCol) {
if (minRow < maxCR) {
dr = -1;
dc = 0;
}
} else if (r == minRow && c == maxCR) {
dr = 1;
dc = 0;
}
}
return result;
}
};