Home > Computer Programming > Printing an Array in Spiral Order !

Printing an Array in Spiral Order !

Hello !

Once I had to write a code to print an N*N array in spiral order. Well it was a really thinkable process to get to the solution and this problem was also asked in Microsoft interviews. So here I go with the C# code to print an array in spiral order,

public void PrintInSpiral(int [][] numbers, int size)
{
for(int i = size – 1 , j = 0 ; i >= 0 ; i–, j++)
{
for(int k = j ; k < i; k++)
Console.Write(numbers[j][k]+ " ");
for(int k = j ; k < i; k++) 

Console.Write(numbers[k][i]+ " ");
for(int k = i ; k > j; k–)
Console.Write(numbers[i][k]+ " ");
for(int k = i ; k > j; k–)
Console.Write(numbers[k][j]+ " ");
}
}

if the array has a rank of 4 and contains elements as follows.

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

then the output should be 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10. So run the above code and do dry run it on any N*N array :)

Regards,
Haroon

About these ads
Categories: Computer Programming
  1. Sandeep Singh
    July 30, 2007 at 10:32 am | #1

    Hi Haroon,

    Will this code work fine for square matrix with odd size??? say for 3×3 matrix!!!

    Please conform.

    Thanks

    • Deepthi
      August 6, 2009 at 10:15 am | #2

      can u tell if a matrix spirally can be printed if matrix is m * n

  2. Naveen
    August 23, 2007 at 11:19 am | #3

    Hi sandeep
    For odd size the code wont print the middle value(for ex:in 5*5.. a[2][2] value);
    you can add this to print:
    float i =ar.length%2;// For odd numbers
    if (i!=0){
    int k=(int)((ar.length-i)/2);
    System.out.println(ar[k][k]);
    }

    Thanks
    Naveen

  3. WrongCode
    August 30, 2007 at 8:45 am | #4

    Hmm the code is Wrong it’s not written in c#

    for(int k = i ; k > j; k–)? it should be k–…etc wring code :) sorry but if u kindly post ur correct code, or never do that ;)

    • Oskar
      February 21, 2013 at 2:56 pm | #5

      It’s his crappy scripts that are changing double dash to a long dash instead.. your code looks wrong too.. Mathematicians make bad frontend developers.. people don’t get that..

  4. Hyung Kim
    April 9, 2008 at 3:33 pm | #6

    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Collections;
    using System.Text;

    namespace Microsoft.SpiralBusted
    {
    class Program
    {
    #region SETUP ARRAY
    public const int ROW_SIZE = 5;
    public const int COLUMN_SIZE = 6;

    static int[,] Array = new int[ROW_SIZE, COLUMN_SIZE]
    { {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} };
    #endregion

    #region TRAVERSE FUNCTION
    public static void Traverse(int m, int n, bool bGoingUP)
    {
    // print the current node ignore visited node
    if (Array[m, n] != -1)
    {
    Console.Write(“{0} “, Convert.ToString(Array[m, n]));
    }

    // mark the current node as visited
    Array[m, n] = -1;

    // Recurse right
    if ((n < COLUMN_SIZE-1) && (Array[m, n + 1] != -1) && !bGoingUP)
    {
    Traverse(m, n + 1, false);
    return;
    }

    // Recurse down
    if ((m 0) && (Array[m, n - 1] != -1) && !bGoingUP)
    {
    Traverse(m, n – 1, false);
    return;
    }

    // Recurse up
    // Note: without bGoingUp controller, it will traverse in zigzag style rather than spiral.
    if ((m > 0) && (Array[m - 1, n] != -1))
    {
    Traverse(m – 1, n, true);
    return;
    }

    // make another round till it’s finished
    if ((m < ROW_SIZE – 1) && (n < COLUMN_SIZE – 1))
    {
    Traverse (m, n+1, false);
    }
    }
    #endregion

    #region MAIN
    static void Main(string[] args)
    {
    Traverse(0, 0, false);
    Console.ReadLine();
    }
    #endregion
    }
    }

    Recursive solution…
    -hkim

  5. Hyung Kim
    April 9, 2008 at 3:37 pm | #7

    Depending where you start and how you order recursive calls, it can generate different patterns such as zig-zag… not just spiral.

    -hkim

  6. atanas
    July 12, 2008 at 8:15 pm | #8

    I try to work this program , but I contain exeption!

    // Recurse down
    if ((m (Don’t see) 0) && (Array[m, n - 1] != -1) && !bGoingUP)
    {
    Traverse(m, n – 1, false);
    return;
    }

  7. October 14, 2008 at 10:51 pm | #9

    Gm09KJ gkosir7v2bcakf8Gsbv420Vs

  8. angel
    October 22, 2008 at 12:01 pm | #10

    hi can u help me with the full code please…i need to wryt it in c++

  9. Dior
    June 3, 2009 at 2:11 pm | #11

    Could this work in Java? I’m trying to create the same idea but in reverse order, please help?

  10. August 8, 2009 at 5:39 pm | #12

    It help me. Thank you a lot. ;)

    @angel, I’ll show you hot it works in C++. I’ll be back with a post in 30 mins. :)

  11. pac
    September 18, 2009 at 11:00 am | #13

    nice work , but can you translate this in pascal for me?
    public void PrintInSpiral(int [][] numbers, int size)
    {
    for(int i = size – 1 , j = 0 ; i >= 0 ; i–, j++)
    {
    for(int k = j ; k < i; k++)
    Console.Write(numbers[j][k]+ " ");
    for(int k = j ; k j; k–)
    Console.Write(numbers[i][k]+ ” “);
    for(int k = i ; k > j; k–)
    Console.Write(numbers[k][j]+ ” “);
    }
    }

  12. October 23, 2009 at 7:18 am | #14

    Here is another approach to solve this problem.
    It uses recursion to print the matrix
    http://dev-interview-questions.blogspot.com/2009/03/print-2d-array-matrix-spiral-order.html

  13. om
    December 19, 2009 at 7:18 am | #15

    /*Here is the whole c++ code for this*/
    #include
    using namespace std;
    void spiral_way(int Row_size,int Column_size,int a[][4])
    {
    int i,j,d,Current_row_size,Current_column_size;
    int Counter=Row_size*Column_size;

    Current_row_size =Row_size;
    Current_column_size=Column_size;
    d=0;
    while(Counter>0) //Initailly my “Counter” is set to total no. of elemnet in my 2-D array. so now I will decrement it as I cover a element.
    {
    i=d;j=d;
    while(j<Current_column_size) //this is for printing the first row in forward direction.
    {
    printf("%d\t",a[i][j]);
    j++;
    Counter–;
    }
    j–;i++;
    while(i=d) //this is for printing the last row in backward direction.
    {
    printf(“%d\t”,a[i][j]);
    j–;
    Counter–;
    }
    i–;j++;
    while(i>d) //this is for printing the first column in upward direction.
    {
    printf(“%d\t”,a[i][j]);
    i–;
    Counter–;
    }
    d++; //When I completed the outer rectangle I move in to inner rectangle by incrementing “d” .
    Current_row_size–; //and decrementing the “Current_row_size” and “Current_column_size”.
    Current_column_size–;
    }
    }
    //————————-
    int main()
    {
    int a[5][4]={{1,2,3,4},
    {5,6,7,8},
    {9,10,11,12},
    {13,14,15,16},
    {17,18,19,20}
    };
    spiral_way(5,4,a);
    system(“pause”);
    return 0;
    }

    • om
      December 19, 2009 at 7:33 am | #16

      /*the right one…..*/
      void spiral_way(int Row_size,int Column_size,int a[][4])
      {
      int i,j,d,Current_row_size,Current_column_size;
      int Counter=Row_size*Column_size;

      Current_row_size =Row_size;
      Current_column_size=Column_size;
      d=0;
      while(Counter>0) //Initailly my “Counter” is set to total no. of elemnet in my 2-D array. so now I will decrement it as I cover a element.
      {
      i=d;j=d;
      while(j<Current_column_size)//this is for printing the first row in forward direction.
      {
      printf("%d\t",a[i][j]);
      j++;
      Counter–;
      }
      j–;i++;
      while(i=d)//this is for printing the last row in backward direction.
      {
      printf(“%d\t”,a[i][j]);
      j–;
      Counter–;
      }
      i–;j++;
      while(i>d)//this is for printing the first column in upward direction.
      {
      printf(“%d\t”,a[i][j]);
      i–;
      Counter–;
      }
      d++; //When I completed the outer rectangle I move in to inner rectangle by incrementing “d” .
      Current_row_size–;//and decrementing the “Current_row_size” and “Current_column_size”.
      Current_column_size–;
      }
      }

  14. Rupesh Kumar
    April 7, 2010 at 1:39 pm | #17

    Hi All,

    I made some modification in the same function, to work on asymmetric metrics.

    This code is in Java.

    public static void PrintInSpiral(int [][] numbers, int row, int col)
    {
    int k=0,i=0,j=0,m=0;
    for( i = col- 1, m=row-1 , j = 0 ; i >= 0&& m>=0 && j<(col-1) && j<(row-1) ;m–, j++,i–)
    {
    for( k = j ; k < i; k++)
    System.out.print(numbers[j][k]+ " ");
    for( k = j ; k j; k–)
    System.out.print(numbers[m][k]+ ” “);
    for( k = m ; k > j; k–)
    System.out.print(numbers[k][j]+ ” “);
    }
    if(row==col&& row%2!=0){
    k=(int)((row-1)/2);
    System.out.print( numbers[k][k]);
    }
    System.out.println();
    }

    • Shilpa
      November 25, 2011 at 3:54 pm | #18

      This prog. is not working. There are many syntax errors…. can u pls post a working program… wich is syntatically correct…..

  15. Martin Babicek
    November 28, 2010 at 3:20 pm | #19

    You are READING spiral, and printing output in line. Unfortunately I need to print spiral, not line. I need output like:
    from:
    1 2 3 4
    5 6 7 8
    9 10 11 12
    13 14 15 16
    to:
    1 2 3 4
    12 13 14 5
    11 16 15 6
    10 9 8 7
    So I need really PRINT spiral. :-(

  16. vishnu
    November 11, 2011 at 8:31 am | #20

    plz give full code of this & properly

  17. September 3, 2012 at 5:06 pm | #21

    please give the code to accept numbers in a M*N matrix in spiral way
    In blue j

  18. My eyes
    March 12, 2013 at 7:12 am | #22

    are bleeding.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: