例:在n*n方阵里输入1,2,3,...,n*n,要求填成蛇形。例如n=4时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
上面的方阵中,多余的空格知识为了便于观察矩阵,不必严格输出,n<=8。
解:此题需要小小地思考下:在按蛇形填充矩阵的过程中,我们注意到这个固定的过程:下、左、上、右、下、左、上、右... ...这个过程是循环的,也就是说我们找到了解决问题的规律~接下来只要模拟这个过程就可以了!
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#include<stdio.h>
#include<string.h>
int a[10][10];
int main()
{
int i, j, n, count;
memset(a, 0, sizeof(a));
scanf("%d", &n);
count = a[i = 1][j = n] = 1;//赋初值,方向为:右->左
while(count < n*n)
{
while(i<n &&="" !a[i+1][j])="" a[++i][j]="++count;//下" while(j="">1 && !a[i][j-1]) a[i][--j] = ++count;//左
while(i>1 && !a[i-1][j]) a[--i][j] = ++count;//上
while(j<n &&="" !a[i][j+1])="" a[i][++j]="++count;//右" }="" for(i="1;" i="" <="n;" i++)="" for(j="1;" j="" j++)="" {="" if(j="=" n)="" printf("%3d\n",="" a[i][j]);="" else="" printf("%3d",="" return="" 0;="" pre="">在填充每个方向时,判断下一个位置是否合适(越界或已填充)~<p></p>
<p>运行结果:</p>
<p><img src="http://www.ctocto.com/uploadfile/Collfiles/20140410/2014041010073029.jpg" alt="" style="width: 630px; height: 205.11627906976744px;"><br>
<br>
</p> </n></n></string.h></stdio.h>
|