定义左边界右边界(由矩阵的性质可得,左边界也是上边界、右边界也是下边界),以左边界作为循环条件,循环打印即可:
// // 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; } };