Experiment 7-2-9 Spiral Square Matrix

Experiment 7-2-9 Spiral Square Matrix

insert image description here

Ideas:

This question is scary at first glance, but if you look closely, the rules of each circle are the same. We can regard the matrix as a circle. In a circle, only the first row (from left to right), the last column (from top to bottom), the last row (from right to left), and the first column (from bottom to top) need to be processed in sequence. After processing, the inner circle is processed recursively in turn. until only one element remains.

the code

#include<stdio.h>
int a[10][10],num = 1;

void spiral(int n,int begin){
    
    
    if(n<1) return;
    if(n==1) {
    
    
        a[begin][begin] = num++;
        return;
    }
    //第一行     
    for(int i = begin;i<n+begin-1;i++)
        a[begin][i] = num++;
    //最后一列
    for(int j = begin;j<n+begin-1;j++)
        a[j][n+begin-1] = num++;
    //最后一行
    for(int j = n+begin-1;j>begin;j--)
        a[n+begin-1][j] = num++;
    //第一列
    for(int j=n+begin-1;j>begin;j--)
        a[j][begin] = num++;
    spiral(n-2,begin+1);
    
}
int main(){
    
    
    int n;
    scanf("%d",&n);
    spiral(n,0);
    for(int i=0;i<n;i++){
    
    
        for(int j=0;j<n;j++)
            printf("%3d",a[i][j]);
        printf("\n");
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/Kilig___/article/details/128113212