蛇形方阵-只有代码

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
    int a[100][100]={}, n, x, y, num=1, i=0;
    cin >> n;
    //memset(a, 0, sizeof(0));
    x = 0, y = n-1;
    a[x][y] = num;
    while(num < n*n)
    {
        // 向下:
        while(x+1 < n && a[x+1][y] == 0)
        {
            num++;
            a[x+1][y] = num;
            i++;
            x++;
        } 
        // x = 3, y = 3;
        // 向左: 
        while(y-1 >= 0 && a[x][y-1]==0)
        {
            num++;
            a[x][y-1]=num;
            y--;
            i++;
        }
        // x = 3, y = 0;
        // 向上: 
        while(x-1 >= 0 && a[x-1][y] == 0)
        {
            num++;
            a[x-1][y]=num;
            x--;
            i++;
        }
        // x = 0, y = 0;
        // 向右:
        while(y+1 < n && a[x][y+1]==0)
        {
            num++;
            a[x][y+1]=num;
            y++;
            i++;
        }
        //cout << x << " " << y << endl;
        if(i==n*n) break;    
    }
    
    for(int i=0; i<=n-1; i++)
    {
        for(int j=0; j<=n-1; j++)
        {
            printf("%2d ", a[i][j]);
        }
        cout << endl;
    }
    return 0;
} 

 

#include<iostream>
using namespace std;

int main()
{
    int a[100][100] = {}, n;
    // 输入
    cin >> n;
    // 出发位置:第一行最后一列。 
    int x=0, y=n-1, num=1; 
    a[x][y] = num;
    // 处理算法
    while(num < n*n)
    {
        // 向下:x行数递增,y列数不变。 
        while(x+1 < n && a[x+1][y]==0)
        {
            num++;
            a[x+1][y] = num;
            x++;
        }
        // x=3 y=3 
        // 向左:x行不变,y列变小。
        while(y-1 >= 0 && a[x][y-1]==0) 
        {
            num++;
            a[x][y-1] = num;
            y--;
        }
        // x=3 y=0
        // 向上:x行数变小,y列数不变。
        while(x-1>=0 && a[x-1][y]==0)
        {
            num++;
            a[x-1][y] = num;
            x--;
        }
        // x=0 y=0
        // 向右:x行数不变,y列数变大。
        while(y+1<n  && a[x][y+1]==0) 
        {
            num++;
            a[x][y+1] = num;
            y++;
        }
    }
        // x=0 y=2
        //cout << "x=" << x << " " << "y=" << y << endl;
    // 输出
    for(int i=0; i<=n-1; i++)
    {
        for(int j=0; j<=n-1; j++)
        {
            printf("%2d ", a[i][j]);
        }
        cout << endl;
    }
    return 0;
}

 

posted @ 2023-04-12 18:23  Hi,小董先生  阅读(55)  评论(0)    收藏  举报