59. Spiral Matrix II
2016-12-01 10:11
274 查看
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:
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[][] a = new int ; if(n == 0) return a; if(n == 1) { a[0][0] = 1; return a; } int top = 0; int bottom = n -1; int left = 0; int right = n - 1; int num = 1; while(top <= bottom && left <= right){ //right to left in top for(int i = left ; i <= right ; i++){ a[top][i] = num; num++; } top++; //top to bottom in right for(int i = top ; i <= bottom ; i++){ a[i][right] = num; num++; } right--; // right -> left in bottom if(bottom >= top){ for(int i = right ; i >= left ; i--){ a[bottom][i] = num; num++; } bottom--; } //bottom -> top in left if(right >= left){ for(int i = bottom ; i >= top ; i--){ a[i][left] = num; num++; } left++; } } return a; } }
相关文章推荐
- LeetCode 59 Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- 【LeetCode】59. Spiral Matrix II
- leetcode 59:Spiral Matrix II
- (Java)LeetCode-59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- Middle-题目29:59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 【leetcode】59.Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode 59 - Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II && 54. Spiral Matrix
- 【LeetCode】(59)Spiral Matrix II(Medium)
- 【LeetCode】C# 59、Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- 59. Spiral Matrix II