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

Comments (0)
Trackbacks (0)
Leave a comment
Trackback