Home > Arrays, Iteration > Spiral traversal of a matrix

Spiral traversal of a matrix

Duh! This is a no-brainer. But since it might be useful to select few out there, here goes.

Problem Statement: You have a 2D matrix. Print its elements while traversing in a spiral manner.

Example –

1 2 4 6

5 3 8 9

4 5 6 7

9 6 4 1

Now your output should be of the form,

1 2 4 6 9 7 1 4 6 9 4 5 3 8 6 5

( You get it, right? )

So all you need to do is

0. increase COLUMN, “N” times (for a NxN) matrix

1. increment ROW, N-1 times

2. decrement COLUM, N-1 times

3. decrement ROW, N-2 times

4. increment COLUMN, N-2 times

5. (Repeat the process)

That is it! Next one will be a toughie. Gear up! 🙂

Advertisements
Categories: Arrays, Iteration Tags: ,
  1. No comments yet.
  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

%d bloggers like this: