59. Spiral Matrix II
2017-08-25 17:22
351 查看
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:
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) { int startx = 0,starty = 0,endx = n-1,endy = n-1; int[][] ans = new int ; int count = 1; while(startx <= endx && starty <= endy){ for(int i = startx;i<=endx;i++){ ans[starty][i] = count++; } starty++; for(int i = starty;i<=endy;i++){ ans[i][endx] = count++; } endx--; for(int i = endx;i>=startx;i--){ ans[endy][i] = count++; } endy--; for(int i = endy;i>=starty;i--){ ans[i][startx] = count++; } startx++; } return ans; } }
相关文章推荐
- LeetCode 59 Spiral Matrix II(螺旋矩阵II)(Array)
- leetcode 59:Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode_59---Spiral Matrix II
- LeetCode------54. Spiral Matrix(螺旋二维矩阵)-----59. Spiral Matrix II(n的螺旋矩阵)
- leetcode[59]Spiral Matrix II
- Leetcode 59. Spiral Matrix II
- 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- leetcode——59——Spiral Matrix II
- leetcode 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode.54(59) Spiral Matrix && II
- leetcode 59: Spiral Matrix II
- 【leetcode】59. Spiral Matrix II
- [leetcode] 59.Spiral Matrix II
- [LeetCode]59 Spiral Matrix II
- 59. Spiral Matrix II