spiral-matrix-ii 1.0.0
Spiral Matrix II
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
6{
7public:
8 vector<vector<int>> generateMatrix(int n)
9 {
10 vector<vector<int>> matrix(n, vector<int>(n));
11
12 int left = 0, right = n - 1, top = 0, bottom = n - 1;
13 int num = 1;
14 while (left <= right && top <= bottom)
15 {
16 for (int j = left; j <= right; ++j)
17 matrix[top][j] = num++;
18 ++top;
19
20 for (int i = top; i <= bottom; ++i)
21 matrix[i][right] = num++;
22 --right;
23
24 if (top <= bottom)
25 {
26 for (int j = right; j >= left; --j)
27 matrix[bottom][j] = num++;
28 --bottom;
29 }
30
31 if (left <= right)
32 {
33 for (int i = bottom; i >= top; --i)
34 matrix[i][left] = num++;
35 ++left;
36 }
37 }
38 return matrix;
39 }
40};
41
42int main()
43{
44 vector<vector<int>> matrix = Solution().generateMatrix(3);
45 for (vector<int>& row: matrix)
46 {
47 for (int element: row)
48 cout << element << " ";
49 cout << endl;
50 }
51 return 0;
52}
vector< vector< int > > generateMatrix(int n)
Definition main.cpp:8
int main()
Definition main.cpp:42