59. Spiral Matrix II
2017-09-20 11:43
253 查看
题目
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 ]
]
思路
这道题目又是螺旋遍历,思路和前面一篇博客:Spiral Matrix一模一样就不多说了,直接上代码:
代码
class Solution { public: vector<vector<int>> generateMatrix(int n) { //生成n*n的数组 vector<int> tmp(abs(n),1); vector<vector<int>> matrix; if (n==0) return matrix; for(int j=0;j<abs(n);j++) matrix.push_back(tmp); int rowbegin = 0,rowend=matrix.size()-1,colbegin=0,colend = matrix[0].size()-1; int num =1; while(rowbegin<=rowend&&colbegin<=colend)//大循环 { for(int i=colbegin;i<=colend;i++)//从左往右 { matrix[rowbegin][i] =num ; num++; } rowbegin++; for(int i=rowbegin;i<=rowend;i++)//从上至下 { matrix[i][colend] =num; num++; } colend--; if(rowbegin<=rowend) { for(int i=colend;i>=colbegin;i--)//从右往左 { matrix[rowend][i] = num; num++; } } rowend--; if(colbegin<=colend) { for(int i=rowend;i>=rowbegin;i--)//从下往上 { matrix[i][colbegin]=num; num++; } } colbegin++; } return matrix; } };
相关文章推荐
- 59. Spiral Matrix II
- Leetcode:59. Spiral Matrix II
- 54 59. Spiral Matrix I II
- 59. Spiral Matrix II
- 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】【59】Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode 59: Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode(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
- 59 Spiral Matrix II