Leetcode 59. Spiral Matrix II

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Spiral Matrix II

2. Solution

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
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int total = n * n;
vector<vector<int>> matrix;
for(int i = 0; i < n; i++) {
vector<int> row(n, 0);
matrix.push_back(row);
}
for(int i = 0, j = 0, count = 0; count < total; i++, j++) {
// top
for(int k = j; k < n - j; k++) {
matrix[i][k] = ++count;
}
// right
for(int k = i + 1; k < n - i; k++) {
matrix[k][n - 1 - j] = ++count;
}
// bottom
for(int k = n - 2 - j; k >= j; k--) {
matrix[n - 1 - i][k] = ++count;
}
// left
for(int k = n - 2 - i; k > i; k--) {
matrix[k][j] = ++count;
}
}
return matrix;
}
};

Reference

  1. https://leetcode.com/problems/spiral-matrix-ii/description/
如果有收获,可以请我喝杯咖啡!