Skip to content

Commit dc4ec54

Browse files
committed
打印螺旋方阵
1 parent 470e05d commit dc4ec54

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

dfs/SnakeMatrix.cpp

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
5+
/*打印螺旋方阵
6+
请输入数组长度:5
7+
1 2 3 4 5
8+
16 17 18 19 6
9+
15 24 25 20 7
10+
14 23 22 21 8
11+
13 12 11 10 9
12+
*/
13+
int main()
14+
{
15+
int num = 1;
16+
int n = 0;
17+
int i, j;int nextI, nextJ = 0;
18+
//Right,Down,Left,Up
19+
int direction[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
20+
//当前的方向
21+
int d = 0;
22+
23+
printf("请输入数组长度:");
24+
scanf("%d", &n);
25+
int **matrix = (int **)malloc(sizeof(int) * n);
26+
for (i = 0; i < n; i++)
27+
{
28+
matrix[i] = (int *)malloc(sizeof(int) * n);
29+
}
30+
//memset(matrix, 0, sizeof(int) * n * n); not work
31+
32+
//清0
33+
for (i = 0; i < n; i++)
34+
{
35+
memset(matrix[i], 0, sizeof(int) * n);
36+
}
37+
38+
i = j = 0;
39+
while (num <= n * n)
40+
{
41+
matrix[i][j] = num;
42+
nextI = i + direction[d][0];
43+
nextJ = j + direction[d][1];
44+
//若出界,或者下一步已经走过,则转方向
45+
if (nextI < 0 || nextI >= n || nextJ < 0 || nextJ >= n || matrix[nextI][nextJ] !=0)
46+
{
47+
//转方向
48+
d = (d + 1) %4;
49+
}
50+
i = i + direction[d][0];
51+
j = j + direction[d][1];
52+
num++;
53+
}
54+
55+
for (i = 0; i < n; i++)
56+
{
57+
for (j = 0; j < n; j++)
58+
{
59+
printf("%3d", matrix[i][j]);
60+
}
61+
printf("\n");
62+
}
63+
64+
return 0;
65+
}
66+

0 commit comments

Comments
 (0)