Print Matrix in Spiral order OR Given m*n matrix(m rows, n columns), print all elements of the matrix in spiral order ORPrint two-dimensional array in spiral order ORHow to print elements of Matrix in Spiral Format?Given a Matrix(2D array), print it in spiral form. Lets understand the problem statement graphically and it will be more clear,

Algorithm

There are 2 ways to print matrix in Spiral order.

Iterative.

Recursive.

In this approach, we will focus on Iterative approach.

In Iterative approach, we need to maintain 4 variables rowStart, rowLength, colStart, colLength which help in printing matrix in Spiral way.

Left to Right.Move variable i from rowStart till colLength. (Print data from first row till last column.)

Top to Bottom. Move variable i from (rowStart+1) till rowLength. (Print data in last column till)We need to start from (rowStart+1) because, we already printed corner element in Left to Right printing and no need to include it again. Same treatment for corner elements in other directions.

Right to Left.Move variable i from colLength-1 till colStart. (Print data in last row)

Bottom to Up.Move variable i from rowLength-1 till rowStart. (Print data in first column)

After printing all 4 directions, In next iteration, we need to start from second row and second column, so increment (rowStart ++) and (colStart++).we need to print till second Last column and till second Last row, so decrement (colLength --) and (rowLength --).

You can compare Printing Matrix in Spiral form to Peeling an onion.

First, you peel off the outer-layer skin (Print outer matrix). After the first layer is peeled off, there’s another layer to peel (Print inner matrix).

So you peel off the remaining onion again until there is no more to peel, which is where you stop.(In our case we stop when rowStart meets rowLength or colStart meets colLength).

Post a Comment

I'm Jayesh Patel, author of "JavaByPatel". I'm not a professional blogger but when time permits, love to share in-depth solutions to common Interview questions asked.Any questions/feedback, Please drop a mail atjayeshmaheshpatel@gmail.com