Spiral Order Matrix II - The Coding Shala
Home >> Interview Questions >> Spiral Order matrix 2
Spiral Order Matrix II Problem Solution
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
The concept is the same as how to print the Spiral Order Matrix.
Let's see for n= 4, then numbers will come from 1 to 16(n*n) in the matrix.
As we need to insert numbers in spiral order so here we need 4 things to check, first and last column and top and bottom row. The following four steps we need to do:
- First, we need to insert numbers in the top row. Our loop will go from the left column to the right then will increase the top row by one and now the top is our second row.
- Now we are inserting the numbers in the right column, will start the loop from top to bottom, and then decrease the value of the right column by one. Now our right column is n-1 and so on later steps.
- Now insert the numbers in the bottom row. the loop will go from right to left and then decrease the value of the bottom. the bottom will go up.
- The last step is to insert the number in the left column. Loop will go from bottom to top row and then increase the value of the left column by one.
Once we follow all the above steps(one time) our outer layer is done all the left, right, top, bottom value updated. Follow these steps until left<=right and top<=bottom(outer loop).
Other Posts You May Like