Home >> Interview Questions >> Spiral Order matrix 2 Spiral Order Matrix II Problem Solution Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order. Example: Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] Solution: (Java) The concept is the same as how to print the Spiral Order Matrix. Approach: 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 ...
Comments
Post a Comment