1 条题解

  • 0
    @ 2023-6-11 12:16:28

    C :

    #include <stdio.h>
    #include <memory.h>
    int main(){
    	int n;
    	scanf("%d",&n);
    	int i, c = 0, r = 0,num = 0,cnt = n/2;
    	int a[n][n];
    	memset(a,0,sizeof(a));	//初始化
    	while(cnt--){
    	for (i=r; i<n-c; i++)    //→
    		a[r][i] = ++num;
    	r++;
    	for (i=r; i<n-c; i++)    //↓
    		a[i][n-c-1] = ++num;
    	c++;
    	for (i=c-1; i<n-c; i++)    //←
    		a[n-r][n-i-2] = ++num;
    	for (i=r; i<n-r; i++)        //↑
    		a[n-1-i][c-1] = ++num;
    }	
    	if(n%2!=0)            //如果是奇数,填上正中间那个数
    		a[n/2][n/2] = ++num;
    	for (int i =0; i<n; i++){  //遍历输出
    		for (int j =0; j<n; j++)
    			printf("%3d",a[i][j]);
    	printf("\n");
    	}
    return 0;
    }
    
    

    C++ :

    #include<iostream>
    using namespace std;
    int main(){
    	int n,i,j,s=1,k,a,t,h=0;
        cin>>n;
        int b[n][n];
        k=n-1;
        for(i=0;i<n;i++){
        	for(j=0;j<n;j++) b[i][j]=0;
    	}
        for(j=0;j<n;j++){
        	b[0][j]=s;
        	s++;
    	}
    	for(a=1;a<=n/2;a++){
    		for(t=0;t<k;t++){
    			if(b[a+t][n-a]!=0){
    				h=1;
    				break;
    			}else{
    				b[a+t][n-a]=s;
    				s++;
    			}	
    		}
    		for(t=1;t<=k;t++){
    			if(b[a+k-1][n-a-t]!=0){
    				h=1;
    				break;
    			}else{
    				b[a+k-1][n-a-t]=s;
    				s++;
    			}
    		}
    		k--;
    		for(t=1;t<=k;t++){
    			if(b[a+k-t][n-a-k-1]!=0){
    				h=1;
    				break;
    			}else{
    				b[a+k-t][n-a-k-1]=s;
    				s++;	
    			}
    			
    		}
    		for(t=1;t<=k;t++){
    			if(b[a][n-a-k-1+t]!=0){
    				h=1;
    				break;
    			}else{
    				b[a][n-a-k-1+t]=s;
    				s++;	
    			}
    		}
    		k--;
    		if(h==1) break;
    	}
    	for(i=0;i<n;i++){
    		for(j=0;j<n;j++) printf("%3d",b[i][j]);
    		cout<<endl;
    	}
    }
    

    Python :

    n=int(input())
    a=[[0 for i in range(n)] for j in range(n)]
    k=0
    for i in range(n//2+1):
        for j in range(i,n-i):
            k=k+1
            a[i][j]=k
        for j in range(i+1,n-i):
            k=k+1
            a[j][n-i-1]=k
        for j in range(n-i-2,i-1,-1):
            k=k+1
            a[n-i-1][j]=k
        for j in range(n-i-2,i,-1):
            k=k+1
            a[j][i]=k
    for i in range(n):
        for j in range(n):
            print("%3d"%a[i][j],end="")
        print()
    
    • 1

    信息

    ID
    2144
    时间
    1000ms
    内存
    16MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者