Thursday, August 4, 2011

Spiral Display of a 2-D Matrix


Its one of the common interview questions where you will be asked to display elements of a 2-D matrix Spirally. I was trying to write the code for the same. Over a period of nearly 5 hours. I got something decent.



Code can be found here

The complexity is not so good. If you have any suggestions on improving it, you can comment.

The logic here is :

Traverse the first row and then the last column and then the last row and then the first column.

Then, discard the traversed rows and columns. The matrix will be reduced by 2 rows and 2 columns.
Keep doing this until you fetch the order number of elements in a matrix.

If its a row, column matrix. Don't perform the above operation , just print out the elements.

No comments:

Post a Comment