螺旋矩阵ii
螺旋矩阵-ii
http://www.nowcoder.com/questionTerminal/25ec7a8bf1954a449a13a901e382600d
定义左边界右边界(由矩阵的性质可得,左边界也是上边界、右边界也是下边界),以左边界作为循环条件,循环打印即可:
// // Created by jt on 2020/9/29. // #include <vector> using namespace std; class Solution { public: /** * * @param n int整型 * @return int整型vector<vector<>> */ vector<vector<int> > generateMatrix(int n) { // write code here vector<vector<int>> res(n, vector<int>(n)); for (int left = 0, right = n - 1, current = 1; left <= n / 2; ++left, --right) { // 上 for (int j = left; j <= right; ++j) { res[left][j] = current++; } // 右 for (int j = left + 1; j <= right; ++j) { res[j][right] = current++; } // 下 for (int j = right-1; j >= left; --j) { res[right][j] = current++; } // 左 for (int j = right-1; j > left; --j) { res[j][left] = current++; } } return res; } };
刷遍天下无敌手 文章被收录于专栏
秋招刷题历程