Monday, September 19, 2011

Spiral printing of a two dimensional array

Given a 2D array, print it in spiral form.


Examples
See the following examples.

Input:
        1    2   3   4
        5    6   7   8
        9   10  11  12
        13  14  15  16
Output: 
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 


Input:
        1   2   3   4  5   6
        7   8   9  10  11  12
        13  14  15 16  17  18
Output: 
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11


Code is :
#include <stdio.h>

void spiralPrint(int m, int n, int a[][n])
{

    int i,  k = 0, l = 0;

    m--, n--;

    /*
        k - min row
        m - max row
        l - min column
        n - max column

        i - iterator
    */

    while(k <= m && l <= n){

        for(i = l; i <= n; ++i) {
            printf("%d ", a[k][i]);
        }

        k++;

        for(i = k; i <= m; ++i) {
            printf("%d ", a[i][n]);
        }

        n--;

        if(m >= k) {

            for(i = n; i >= l; --i) {
                printf("%d ", a[m][i]);
            }

            m--;
        }

        for(i = m; i >= k; --i) {
            printf("%d ", a[i][l]);
        }

        l++;
    }


    printf("\n");
}

int main()
{
    printf("1,  2,  3,  4,  5,  6\n");
    printf("7,  8,  9,  10, 11, 12\n");
    printf("13, 14, 15, 16, 17, 18\n");
    printf("19, 20, 21, 22, 23, 24\n");
    printf("25, 26, 27, 28, 29, 30\n");
    printf("35, 36, 37, 38, 39, 40\n\n");

    int a[6][6] = { {1,  2,  3,  4,  5,  6},
                    {7,  8,  9,  10, 11, 12},
                    {13, 14, 15, 16, 17, 18},
                    {19, 20, 21, 22, 23, 24},
                    {25, 26, 27, 28, 29, 30},
                    {35, 36, 37, 38, 39, 40}
                  };

    spiralPrint(6, 6, a);
}




Time Complexity: Time complexity of the above solution is O(mn).

Source : 1

0 comments:

Post a Comment