竞赛讨论区 > 一种做法
头像
cinics
发布于 2020-02-26 15:40
+ 关注

一种做法

#include <stdio.h>

int main(void){
    int n;
    
    scanf("%d", &n);
    
    int a[n][n];
    int i, j;
    int top = 0, bottom = n-1, left = 0, right = n-1;
    
    int k = 1;
    
    while(k <= n*n){
        //从左往右走
        for(i = left; i <= right; i++){
            a[top][i] = k;
            k++;
        }
        top++;
        
        //从上往下走
        for(i = top; i <= bottom; i++){
            a[i][right] = k; 
            k++;
        }
        right--;
        
        //从右往左走
        for(i = right; i >=left; i--){
            a[bottom][i] = k;
            k++;
        }
        bottom--;
        
        //从下往上走
        for(i = bottom; i >= top; i--){
            a[i][left] = k;
            k++;
        }
        left++;
    }
    
    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            printf("%3d", a[i][j]);
        }
        printf("\n");
    }
    
}

全部评论

(0) 回帖
加载中...
话题 回帖

本文相关内容

等你来战

查看全部

热门推荐