leetcode 81: Spiral Matrix II
Spiral Matrix IIMar
28 '12
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
public class Solution { public int[][] generateMatrix(int n) { // Start typing your Java solution below // DO NOT write main() function int[][] res = new int[n][n]; if(n<1) return res; int top=0, bottom=n-1, left=0, right=n-1; int loop = (n+1)/2; for(int i=0, seq=1; i<loop; i++) { for(int j=left; j<=right; j++) { res[top][j] = seq++; } top++; if(top>bottom) return res; for(int j=top; j<=bottom; j++) { res[j][right] = seq++; } right--; if(left>right) return res; for(int j=right; j>=left; j--) { res[bottom][j] = seq++; } bottom--; if(top>bottom) return res; for(int j=bottom; j>=top; j--) { res[j][left] = seq++; } left++; } return res; } }