Printing Matrix (2D array) in Spiral Order

Given a matrix (2D array) of m x n elements (m rows, n columns), write a function that prints the elements in the array in a spiral manner.

If you have done enough training by now, you would have immediately recognized the sub-problems within this problem. When you recognize this property, then you know that this problem is easily solvable with recursion!

Imagine that you are peeling an onion (I know your eye hurts!). First, you peel off the outer-layer skin. After the first layer is peeled off, there’s another layer to peel. So you peel off the remaining onion again until there is no more to peel, which is where you stop.

It’s the same with printing the matrix spirally! Print the outer layer of the matrix, then print the remaining sub-matrix recursively. Please do not forget to handle the base case! (Hint: Check when m == 1 or n == 1).

EDIT: (Added test data)
Below are the input and output data set I created for testing purposes. In the input file, the first line signifies the total number of cases. Then all cases are listed where the the number of row and column are specified first, then followed by elements of all rows and columns.

Attachment:
» Download Input Data Set
» Download Output Data Set

VN:F [1.9.22_1171]
Rating: 4.5/5 (14 votes cast)
Printing Matrix (2D array) in Spiral Order, 4.5 out of 5 based on 14 ratings

27 thoughts on “Printing Matrix (2D array) in Spiral Order

  1. Anonymous

    Is it possible for you to share the test case as well? Whenever I find a problem and try my own solution, I am not sure if it correct or not. Writing test cases on my own is a time consuming operation. If you can provide test case, that would be really helpful for the readers of your website.

    VA:F [1.9.22_1171]
    +2
  2. 1337c0d3r

    Thank you for your comment. I have just updated this page with the input and output data set. You are right, making good test cases is not an trivial task. This is a very good suggestion, I should make it a habit to always create good test cases for all the interview problems here. I will try my best to update other questions with test cases as well.

    VA:F [1.9.22_1171]
    +1
  3. Anonymous

    This is the typical tail recursion and should be easily write the code without using recursion by calculate how many time we need to loop.

    VA:F [1.9.22_1171]
    +1
  4. 1337c0d3r

    Yes you are absolutely right. A tail recursion can always be converted to a loop easily and is not necessary as an iterative solution is more efficient.

    VA:F [1.9.22_1171]
    0
  5. johny

    Hi, 1337:

    Sorry for my dumb. But I have difficulty here in understanding your code. In the function print_spiral(m[][N_MAX], m, n, k), what are the meanings of these parameters? Would you elaborate?

    And I remember in C, if a function has a 2-dimentional array as its parameter, then the array’s 2nd dimension must be fixed, like “f(int daytab[][13]) { … }”. But in your recursion function, the 2nd dimention passed to the function is smaller and smaller, right?

    Could you give me an example on how to call this function?

    Thanks,
    johny

    VA:F [1.9.22_1171]
    0
  6. Pingback: Printing Matrix (2D array) in Spiral Order | 口├人人│의 Blog

  7. KK

    Here’s the iterative and readable code

    VA:F [1.9.22_1171]
    -1
  8. Pingback: Printing M*N Matrix in Spiral Order | This is how Cheng grows up

  9. md

    // print from top right
    for (int i = 0; i < m – 1; i++)
    cout << mat[k+i][k+n-1] << " ";

    Should it not be mat[k+i][n-1-k]? You are reducing the column to the left recursively. right?

    VA:F [1.9.22_1171]
    +1
  10. satish babu atcha

    ///i written in c

    #include
    #define MAX 50
    int main()
    {
    int a[MAX][MAX],i,j,lower,upper,k,n;
    printf(“enter number\n”);
    scanf(“%d”,&n);
    for(i=0;i<n;i++)
    {
    for(j=0;j<n;j++)
    scanf("%d",&a[i][j]);

    }
    i=0;
    j=0;
    lower=0,upper=n-1;
    for(k=0;k<(n*n);k++)
    {
    printf("%d\t",a[i][j]);
    if((i==lower)&&(j<upper))
    j++;
    else if((j==upper)&&(ilower))
    j–;
    else if((j==lower)&&(i>lower))
    i–;
    if((a[i][j]==a[lower][i]))
    {
    lower++;
    upper–;
    i++;
    j++;
    }
    }
    return 0;
    }

    VN:F [1.9.22_1171]
    +2
  11. Pingback: leetcode: Spiral Matrix I and II solution | 烟客旅人 sigmainfy

  12. yy

    Java version of KK’s code with fixes(compile and run able):

    VA:F [1.9.22_1171]
    0
    1. yy

      the code tag won’t prevent codes from been eaten, please view source of this page to get the real codes. I now understand why KK posted crappy code~~.

      VA:F [1.9.22_1171]
      0
  13. Oladipo Fasoro

    Wrote this in Java.

    VA:F [1.9.22_1171]
    0
  14. yun

    java version

    VN:F [1.9.22_1171]
    0
  15. yun

    loss code snippet.

    VN:F [1.9.22_1171]
    0
    1. yun

      public static void spiralPrintArray(int[][] a) {
      int h = a.length, l = a[0].length;
      int c = 0, r = 0, tier = 0;

      while ( c <= l / 2 && r <= h / 2) {
      for (; c < l; c++) {
      System.out.println(a[r][c]);
      }

      c–;
      r++;
      for (; r tier; c–) {
      System.out.println(a[r][c]);
      }

      for (; r > tier; r–) {
      System.out.println(a[r][c]);
      }

      c++;
      r++;
      l–;
      h–;
      tier++;
      }
      }

      VN:F [1.9.22_1171]
      0

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use the <code> tag to embed your code.

*