## 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

Hi Haroon,

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

Please conform.

Thanks

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

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

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

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..

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

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

-hkim

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;

}

Gm09KJ gkosir7v2bcakf8Gsbv420Vs

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

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

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. :)

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]+ ” “);

}

}

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

/*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;

}

/*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–;

}

}

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();

}

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

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. :-(

plz give full code of this & properly

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

In blue j

are bleeding.