Showing posts with label array by reference. Show all posts
Showing posts with label array by reference. Show all posts

Wednesday, June 29, 2011

Spiral order traversal of 2D Array

Someone asked me this question during an interview. I am going to post the code & algorithm here.

Algorithm:


Code : SpiralArray.cpp

 #include<iostream>  
using namespace std;
#define ROWS 5
#define COLS 5
void printSpiral(int (&arr)[ROWS][COLS])
{
static int x=0,y=0;
static int ROW = ROWS;
static int COL = COLS;
for(int i=x;i<ROW;i++)
{
for(int j=y;j<COL;j++)
{
if(i==x)
{
cout<<arr[i][j]<<" ";
}
else if(i==ROW-1)
{
cout<<arr[i][COL-1-j+y]<<" ";
}
else
{
cout<<arr[i][COL-1]<<" ";
break;
}
}
}
--ROW;
--COL;
for(int i=ROW-1;i>x;i--)
{
for(int j=y;j<COL;j++)
{
cout<<arr[i][j]<<" ";
break;
}
}
++x;
++y;
if(x<ROW || y < COL)
{
printSpiral(arr);
}
}
int main()
{
int arr[ROWS][COLS]={{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}};
printSpiral(arr);
cout<<endl;
}


How To Compile:

g++ SpiralArray.cpp -o SpiralArray

Output:

Output of above Example is :
 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
1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6 7 8 9 14 19 18 17 12 13