59. Spiral Matrix II
2017-07-30 15:17
260 查看
题目
生成螺旋矩阵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 ] ]
思路
递归实现code
public class Solution { private int[,] matrix; private int elen; public int[,] GenerateMatrix(int n) { matrix = new int[n, n]; elen = 0; //element count spiral(0, n-1, n-1, 0); return matrix; } private void spiral(int top, int right, int bottom, int left) { if (top > bottom || left > right) return; //add first row for (int j = left; j <= right; j++) matrix[top, j] = ++elen; //add last column for (int i = top + 1; i <= bottom; i++) matrix[i, right] = ++elen; //add last row for (int j = right - 1; j >= left && top != bottom; j--) matrix[bottom, j] = ++elen; //add first column for (int i = bottom - 1; i > top && left != right; i--) matrix[i, left] = ++elen; spiral(top + 1, right - 1, bottom - 1, left + 1); } }
相关文章推荐
- Leetcode:59. Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode 59 - Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- Middle-题目29:59. Spiral Matrix II
- 【LeetCode】59. Spiral Matrix II
- 59. Spiral Matrix II
- 【leetcode】59.Spiral Matrix II
- 54. Spiral Matrix && 59. Spiral Matrix II
- leetcode-59 Spiral Matrix II
- 59. Spiral Matrix II
- Leetcode59 Spiral Matrix II
- 59. Spiral Matrix II && 54. Spiral Matrix
- LeetCode 54/59. Spiral Matrix i, ii
- 59. Spiral Matrix II
- 59. Spiral Matrix II