Skip to content

Commit 44310d9

Browse files
committed
20191114
1 parent 9e3a18e commit 44310d9

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

螺旋矩阵.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <cmath>
4+
using namespace std;
5+
6+
int main()
7+
{
8+
// 矩阵宽度
9+
int n;
10+
cin >> n;
11+
int *e = new int[n * n];
12+
vector<vector<int>> matrix(n, vector<int>(n));
13+
for (int i = 0; i < n * n; i++)
14+
e[i] = i + 1;
15+
int index = 0;
16+
int step = n - 1;
17+
int x = 0, y = 0;
18+
while (step >= 1)
19+
{
20+
for (int i = 0; i < step; i++)
21+
matrix[x][y++] = e[index++];
22+
for (int i = 0; i < step; i++)
23+
matrix[x++][y] = e[index++];
24+
for (int i = 0; i < step; i++)
25+
matrix[x][y--] = e[index++];
26+
for (int i = 0; i < step; i++)
27+
matrix[x--][y] = e[index++];
28+
step -= 2;
29+
x++;
30+
y++;
31+
}
32+
if (n % 2 == 1)
33+
matrix[x][y] = n * n;
34+
for (int i = 0; i < n; i++)
35+
{
36+
for (int j = 0; j < n; j++)
37+
printf("%02d ", matrix[i][j]);
38+
cout << endl;
39+
}
40+
system("pause");
41+
return 0;
42+
}

0 commit comments

Comments
 (0)