在n*n的方阵里填入1,2,..,n*n,要求填成蛇形。例如当n=4时方针为
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
n<=8。
#include <iostream>
#include <cstdio>
#include <string.h>
#define max 20
using namespace std;
int a[max][max];
int main()
{
int n;
while(scanf("%d",&n) != EOF)
{
memset(a,0,sizeof(a));
int x,y,num;
x = 0;
y = n-1;
num = a[x][y] = 1;
while(num < n*n)//如果去等,则意味着num = n*n时还要进入循环,事实上num = n*n时,结果已经做完了
{
while(x+1<n && !a[x+1][y]) a[++x][y] = ++num;//从上往下。这一题难的是条件的判断,while里应该为x+1<n,因为这个时候判断的是下个要填入的位置是否满足条件,以下同理
while(y-1>=0 && !a[x][y-1]) a[x][--y] = ++num;//从右往左
while(x-1>=0 && !a[x-1][y]) a[--x][y] = ++num;//从下往上
while(y+1<n && !a[x][y+1]) a[x][++y] = ++num;//从左往右
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
printf("%3d ",a[i][j]);//为了数字对称,所以让每个输出占三个空格
printf("\n");
}
}
return 0;
}
蛇形填充算法实现
163

被折叠的 条评论
为什么被折叠?



