P40蛇形填数

蛇形填数。在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<bits/stdc++.h>
using namespace std;
int a[100][100];
int main()
{
    int n;
    int count=1;
    scanf("%d",&n);
    memset(a,0,sizeof(a));
    int x=0;
    int y=n-1;
    a[x][y]=1;
    while(count<n*n)
    {
        while(x+1<n&&!a[x+1][y]) a[++x][y]=++count;
        while(y-1>=0&&!a[x][y-1]) a[x][--y]=++count;
        while(x-1>=0&&!a[x-1][y]) a[--x][y]=++count;
        while(y+1<n&&!a[x][y+1]) a[x][++y]=++count;
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            printf("%3d ",a[i][j]);
        }
        printf("
");
    }
    return 0;
}

1.方向:下-左-上-右  四个方向不断循环。

2.原则:先判断,再移动。而不是先走一步发现越界以后再退回来。

3.是++x而不是x+1或者x++;

原文地址:https://www.cnblogs.com/laoyangtou/p/8831814.html