Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
You should return the following matrix:Given n =
3
,[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Solution:
public class Solution { public int[][] generateMatrix(int n) { int sol[][] = new int[n][n]; int count = 0; int row = 0; int col = 0; int direction = 1; //1 to the right, 2 to the bottom, 3 to the lift, 4 to the top while ( count< n*n) { sol[row][col] = ++count; switch(direction) { case 1: col++; if( col >= n-1 || sol[row][col+1] != 0) direction = 2; break; case 2: row++; if( row >= n-1 || sol[row+1][col] != 0) direction = 3; break; case 3: col--; if( col <= 0 || sol[row][col-1] != 0) direction = 4; break; case 4: row--; if( row <= 0 || sol[row-1][col] != 0) direction = 1; break; } } return sol; } }
No comments :
Post a Comment