59. Spiral Matrix II
2016-10-11 15:22
323 查看
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 ]
]
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
#include<iostream> #include<vector> using namespace std; class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int> >result(n,vector<int>(n,0));//注意二维vector初始化 if(0==n) return result; int count=1; int x=0,y=0; result[0][0]=count; while(count<n*n) { while(y+1<n&&!result[x][y+1]) result[x][++y]=++count; while(x+1<n&&!result[x+1][y]) result[++x][y]=++count; while(y-1>=0&&!result[x][y-1]) result[x][--y]=++count; while(x-1>=0&&!result[x-1][y]) result[--x][y]=++count; } return result; } }; int main() { vector<vector<int> >ret; int N; cin>>N; Solution solve; ret=solve.generateMatrix(N); int i,j; for(i=0;i<N;i++) { for(j=0;j<N;j++) cout<<ret[i][j]<<' '; cout<<endl; } return 0; }
相关文章推荐
- 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
- [LeetCode]59 Spiral Matrix II
- 59. Spiral Matrix II
- [LeetCode 59] Spiral Matrix II
- 【LEETCODE】59-Spiral Matrix II
- [LeetCode]59. Spiral Matrix II
- leetcode59-Spiral Matrix II(生成蛇形矩阵)
- leecode 解题总结:59. Spiral Matrix II
- LeetCode59——Spiral Matrix II
- [LeetCode] 59. Spiral Matrix II
- leetcode-java-59. Spiral Matrix II
- Medium 59题 Spiral Matrix II
- 59. Spiral Matrix II LeetCode
- LeetCode 59. Spiral Matrix II
- 59. Spiral Matrix II