Leetcode:59. Spiral Matrix II
2017-05-18 23:19
309 查看
Description
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.Example
Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
思路
没啥好说的,一圈一圈的打印代码
cclass Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n, vector<int>(n, 0)); int start = 0; int sum = 1; while(start * 2 < n){ generate(res, n, start, sum); start++; } return res; } void generate(vector<vector<int>>& res, int n, int start, int &count){ int endCol = n - start - 1; int endRow = n - start - 1; for(int i = start; i <= endCol; ++i) res[start][i] = count++; if(endRow > start){ for(int i = start + 1; i <= endRow; ++i) res[i][endCol] = count++; } if(endCol > start){ for(int i = endCol - 1; i >= start; --i) res[endRow][i] = count++; } if(endRow > start && endCol > start){ for(int i = endRow - 1; i > start; --i) res[i][start] = count++; } } };
相关文章推荐
- 【C++】【LeetCode】54. Spiral Matrix && 59. Spiral Matrix II
- Leetcode 59 Spiral Matrix II
- leetcode59-Spiral Matrix II(生成蛇形矩阵)
- LeetCode 59. Spiral Matrix II
- 【LeetCode】59. Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- LeetCode54/59 Spiral Matrix I/II
- LeetCode 59. Spiral Matrix II
- 个人记录-LeetCode 59. Spiral Matrix II
- 【leetcode】Array——Spiral MatrixII(59)
- (Java)LeetCode-59. Spiral Matrix II
- 【LEETCODE】59-Spiral Matrix II
- leetcode[59]Spiral Matrix II
- Leetcode 59. Spiral Matrix II
- 59. Spiral Matrix II Leetcode Python
- leetcode ----59. Spiral Matrix II
- leetcode——59——Spiral Matrix II
- leetcode-java-59. Spiral Matrix II