【leetcode】Spiral Matrix II
2015-05-03 20:04
429 查看
Given an integer n, generate a square matrix filled with elements from 1 to n^2 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 ]
]
class Solution { public: vector<vector<int> >generateMatrix(int n) { int m=0; vector<vector<int> >a; a.resize(n,vector<int>(n)); if(n==0) return a; int x=0; int y=0; m=a[0][0]=1; while(m<n*n) { while(y<n-1&&!a[x][y+1]) { m++; y++; a[x][y]=m; } while(x<n-1&&!a[x+1][y]) { m++; x++; a[x][y]=m; } while(y-1>=0&&!a[x][y-1]) { m++; y--; a[x][y]=m; } while(x-1>=0&&!a[x-1][y]) { m++; x--; a[x][y]=m; } } return a; } };
相关文章推荐
- leetcode59-Spiral Matrix II(生成蛇形矩阵)
- [leetcode] Spiral Matrix II
- leetcode Spiral Matrix II
- [leetcode]Spiral Matrix II
- LeetCode 94 Spiral Matrix II
- [LeetCode] Spiral Matrix II
- leetcode Spiral Matrix II
- LeetCode - Spiral Matrix II
- [LeetCode]Spiral Matrix II
- leetcode---spiral-matrix-ii---数组
- [LeetCode] Spiral Matrix II
- [Leetcode] 59. Spiral Matrix II
- Leetcode Spiral Matrix II
- Spiral Matrix II -- leetcode
- leetcode 日经贴,Cpp code -Spiral Matrix II
- LEETCODE: Spiral Matrix II
- leetcode59 Spiral Matrix II
- leetcode编程记录18 #59 Spiral Matrix II
- LeetCode: Spiral Matrix II
- LeetCode 58 Spiral Matrix II