leetcode 81: Spiral Matrix II
2013-02-18 08:02
495 查看
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 =
You should return the following matrix:
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,
You should return the following matrix:
[ [ 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 ; 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; } }
相关文章推荐
- leetcode 81: Spiral Matrix II
- LeetCode 94 Spiral Matrix II
- leetcode -- Spiral Matrix II
- LeetCode | Spiral Matrix II(螺旋矩阵填充数据)
- Leetcode: spiral Matrix II.
- [leetcode] Spiral Matrix II
- 【LeetCode】(59)Spiral Matrix II(Medium)
- leetcode Spiral Matrix II
- leetcode 59. Spiral Matrix II
- LeetCode 59: Spiral Matrix II
- LeetCode --- 59. Spiral Matrix II
- leetcode JAVA Spiral Matrix II 难度系数3 3.19
- Leetcode-Spiral Matrix II
- LeetCode(57) SpiralMatrix II
- LeetCode Spiral Matrix II
- LeetCode题解:Spiral Matrix I and II
- [leetcode] Spiral Matrix II
- 【leetcode】【59】Spiral Matrix II
- leetcode[59]Spiral Matrix II
- LeetCode_Spiral Matrix II