59. Spiral Matrix II
2017-02-02 01:36
316 查看
1刷
跟之前那个蛇形一样。。。
2刷
十分好,马上学习了上一题蛇形的做法,手动刷出了这一题,还要3刷练手练思维
跟之前那个蛇形一样。。。
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>>ve; vector<int>v; for(int i = 0; i < n; ++ i) v.push_back(0); for(int i = 0; i < n; ++ i) ve.push_back(v); int layer = (n + 1) / 2; int num = 1; int m = n; for(int i = 0; i < layer; i ++) { //row i: top-left --> top-right for(int j = i; j < n-i; j ++) ve[i][j] = num++; //col n-1-i: top-right --> bottom-right for(int j = i+1; j < m-i; j ++) ve[j][n-1-i] = num++; //row m-1-i: bottom-right --> bottom-left if(m-1-i > i) { for(int j = n-1-i-1; j >= i; j --) ve[m-1-i][j] = num++; } //col i: bottom-left --> top-left if(n-1-i > i) { for(int j = m-1-i-1; j > i; j --) ve[j][i] = num++; } } return ve; } };
2刷
十分好,马上学习了上一题蛇形的做法,手动刷出了这一题,还要3刷练手练思维
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>>dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; vector<vector<int>>ve(n, vector<int>(n, 0)); if(n == 0) return ve; vector<int>step{n, n - 1}; int num = 1; int index = 0; int ir = 0, ic = -1; while(step[index % 2]){ for(int i = 0; i < step[index % 2]; ++ i){ ir += dirs[index][0]; ic += dirs[index][1]; ve[ir][ic] = num++; } step[index % 2]--; index = (index + 1) % 4; } return ve; } };
相关文章推荐
- LeetCode-59-Spiral Matrix II(C语言实现)
- leetcode@ [54/59] Spiral Matrix & Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- leetcode ----59. Spiral Matrix II
- [leetcode-59]spiral matrixII(java)
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- [Leetcode] 59. Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- Array-----59. Spiral Matrix II(蛇形打印矩阵)
- LeetCode 59 Spiral Matrix II
- 59. Spiral Matrix II
- 个人记录-LeetCode 59. Spiral Matrix II
- [4]54. Spiral Matrix/59. Spiral Matrix II(Java)
- LeetCode --- 59. Spiral Matrix II
- Leetcode:59. Spiral Matrix II
- 59. Spiral Matrix II
- leetcode59 Spiral Matrix II