Spiral matrix, spiral

Source: Internet
Author: User

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;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.