2 solutions

  • 3
    @ 2023-10-2 13:10:30
    using namespace std;
    int num[25][25],n;
    int main(){
    	cin>>n;
    	num[1][n]=1;//初始为1
    	for(int i=1,j=n,tot=1;tot<n*n;){//一直填到n*n个数填完
    		while(++i<=n&&!num[i][j])num[i][j]=++tot;--i;//向下
    		while(--j> 0&&!num[i][j])num[i][j]=++tot;++j;//向左
    		while(--i> 0&&!num[i][j])num[i][j]=++tot;++i;//向上
    		while(++j<=n&&!num[i][j])num[i][j]=++tot;--j;//向右
    	}
    	for(int i=1;i<=n;++i,cout<<endl)for(int j=1;j<=n;++j)
    	cout<<num[i][j]<<" ";//输出
    	return 0;
    }
    
    • 1
      @ 2023-11-21 19:09:32
      #include <bits/stdc++.h>
      using namespace std;
      int a[25][25];
      int main(int argc, char **argv){
      	int n;
      	cin >> n;
      	for (int i = 1,j = n,ot = 1;ot <= n * n;){
      		while (i <= n && !a[i][j]){
      			a[i++][j] = ot++;
      		}i--;j--;
      //		printf("i:%d j:%d ot:%d ",i,j,ot);
      		while (j > 0 && !a[i][j]){
      			a[i][j--] = ot++;
      		}j++;i--;
      //		printf("i:%d j:%d ot:%d ",i,j,ot);
      		while (i > 0 && !a[i][j]){
      			a[i--][j] = ot++;
      		}i++;j++;
      //		printf("i:%d j:%d ot:%d ",i,j,ot);
      		while (j <= n && !a[i][j]){
      			a[i][j++] = ot++;
      		}j--;i++;
      //		printf("i:%d j:%d ot:%d ",i,j,ot);
      	}
      	for (int i = 1;i <= n;i++){
      		for (int j = 1;j <= n;j++){
      			printf("%d ",a[i][j]);
      		}
      		cout << "\n";
      	}
      	return 0;
      }
      
      • 1

      Information

      ID
      296
      Time
      1000ms
      Memory
      64MiB
      Difficulty
      7
      Tags
      # Submissions
      152
      Accepted
      36
      Uploaded By