SpiralTraversalOfMatrix


1. Spiral Traversal of a 2D matrix

Problem:

Given a 2D matrix, traverse all it’s elements in a spiral form.
Referring the below matrix as an input (Red line shows a spiral traversal),

output should be: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Solution:

This implementation is done using C#.NET. Rectangular Matrix is declared using int[,] syntax.

public void DoSpiralTraversal(int[,] rectArray)
{
if(rectArray != null && rectArray.Length > 0)
{
Console.WriteLine("Doing Spiral Traversal on a 2D array:");

int noOfElementsTraversed = 0, row_LB = 0, row_UB = rectArray.GetUpperBound(0), col_LB = 0, col_UB = rectArray.GetUpperBound(1), iter;

while (noOfElementsTraversed < rectArray.Length)
{
// Move downwards
for (iter = row_LB; iter <= row_UB; iter++)
{
Console.Write(rectArray[iter,col_LB] + ” “);

noOfElementsTraversed++;
}

col_LB++;

// Move Left to Right
for (iter = col_LB; iter <= col_UB; iter++)
{
Console.Write(rectArray[row_UB, iter] + ” “);

noOfElementsTraversed++;
}

row_UB–;

// Move upwards
for (iter = row_UB; iter >= row_LB; iter–)
{
Console.Write(rectArray[iter, col_UB] + ” “);

noOfElementsTraversed++;
}

col_UB–;

// Move right to Left
for (iter = col_UB; iter >= col_LB; iter–)
{
Console.Write(rectArray[row_LB, iter] + ” “);

noOfElementsTraversed++;
}

row_LB++;
}
}
}

Advertisements

About Sunil Singhal

A human being whose dreams are tied to a Horse that will never tire
This entry was posted in Algorithms and tagged , , , . Bookmark the permalink.

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