Spiral matrix, spiral
To generate the input N and M columns of the matrix so that the rotation is performed.
Assume that the vertical direction is the X axis, the horizontal direction is the Y axis, starting from 1
Layers k = min (I, j, N + 1-i, M + 1-j)
K layer matrix length l = N-(k-1) * 2 w = M-(k-1) * 2
The coordinate value in the upper left corner of the matrix is (k, k). The value can be calculated based on the length and width of the outer matrix to determine the value of the current matrix (I, j ).
Disadvantage: There are many repeated computations in the code. You can record some values to reduce the number of computations.
#include<stdio.h>#define min(x,y) (x)>(y)?(y):(x)int N,M;int foo(int,int);int main(){ while(scanf("%d %d",&N,&M)==2) for(int i=1;i<=N;i++) { for(int j=1;j<=M;j++) { printf("%3d ",foo(i,j)); } printf("\n"); }}int foo(int i,int j){ int k=min( min(i,j) , min(N+1-i,M+1-j) ); int l=N-(k-1)*2, w=M-(k-1)*2; int s=0; for( int t=1;t<k;t++ ) { int l=N-(t-1)*2, w=M-(t-1)*2; s+=(l-1)*2+(w-1)*2; } s++; if(l==1) s+=j-k; else if(w==1) s+=i-k; else { if(i==k) s+=j-k; else if(j==k+w-1) s+=w-1+i-k; else if(i==k+l-1) s+=w-1+l-1+k+w-1-j; else s+=w-1+l-1+w-1+k+l-1-i; } return s;}