简体   繁体   中英

print elements of 2d array in spiral manner

i am trying to print elements of an array in a spiral manner..cant figure out the logical error in my code..

void spiral(int n,int m,int arr[][m])
{
    int t=0,r=m-1,b=n-1,l=0,dir=0; /* t->top b->bottom l->left r->right */
    int k,j;  
    // above parameters to manage the matrix.    

    // exit condition from loop
    while (t<=b && l<=r)
    {
        // print top row
        if (dir==0)                        
        {

            for (k=l;k<=r;k++)
            {
                printf("%d  ",arr[t][k]);

            }
            dir=1;
            t++;

        }

        // print right column
        else if (dir==1)          
        {

            for (k=t;k<=b;k++)
            {
                printf("%d   ",arr[k][r]);

            }
            dir=2;
            r--;

        }

        // print bottom row
        else if (dir==2)             
        {

            for (k=r;k>=l;k--)
            {
                printf("%d   ",arr[b][k]);

            }
            dir=3;
            b--;

        }

        // print left column
        else if (dir==3)         
        {

            for (k=b;k<=t;k--)
            {
                printf("%d   ",arr[k][l]);

            }
            dir=0;
            l++;

        }
    }
}

To accomplish the task there's no need of using variable dir and checking its value as all the steps are repeated in the same order.

There was also an error in the last loop's condition: k <= t should be k >= t .

Here is a possible working implementation:

void spiral(int n,int m,int arr[][m])
{
    int top = 0,            
        right = m - 1,      
        bottom = n - 1,     
        left = 0, 
        k;  

    while( top <= bottom  &&  left <= right )
    {
        //print top row
        for ( k = left; k <= right; k++ )
        {
            printf("%d  ",arr[top][k]);
        }
        ++top;

        //print right column
        for( k = top; k <= bottom; k++ )
        {
            printf("%d   ",arr[k][right]);
        }
        --right;

        //print bottom row
        for( k = right; k >= left; k-- )
        {
            printf("%d   ",arr[bottom][k]);
        }
        --bottom;

        //print left column
        for( k = bottom; k >= top; k-- )
        // this was wrong ^^^^^^ in OP's code
        {
            printf("%d   ",arr[k][left]);
        }
        ++left;
    }
}

Live example HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM