欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

轻松掌握算法实战技巧⑤:ZSTUOJ平台第五期刷题——玩转旋转数阵Problem G

最编程 2024-02-11 18:42:32
...
1 2 3
8 9 4
7 6 5
 1  2  3  4
12 13 14  5
11 16 15  6
10  9  8  7
代码如下:
#include<bits/stdc++.h>
using namespace std;

int main(){
    int a[11][11];
    int n;
    while(~scanf("%d",&n)){
        memset(a,0,sizeof(a));
        int x,y,tot=0;
        a[x=0][y=0]=tot=1;
        while(tot<n*n){
            while(y+1<n&&!a[x][y+1]) a[x][++y]=++tot;
            while(x+1<n&&!a[x+1][y]) a[++x][y]=++tot;
            while(y-1>=0&&!a[x][y-1]) a[x][--y]=++tot;
            while(x-1>=0&&!a[x-1][y]) a[--x][y]=++tot;
        }
        if(n<=3){
            for(x=0;x<n;x++){
                for(y=0;y<n;y++){
                    if(y==0) printf("%d",a[x][y]);
                    else printf("%2d",a[x][y]);
                }
                printf("\n");
            }
        }
        else if(n==10){
            for(x=0;x<n;x++){
                for(y=0;y<n;y++){
                    if(y==0) printf("%3d",a[x][y]);
                    else printf("%4d",a[x][y]);
                }
                printf("\n");
            }
        }
        else{
            for(x=0;x<n;x++){
                for(y=0;y<n;y++){
                    if(y==0) printf("%2d",a[x][y]);
                    else printf("%3d",a[x][y]);
                }
                printf("\n");
            }
        }
    }
    
    return 0;    
}