vector<vector<int>> generateMatrix(int n) { vector<vector<int>> matrix(n, vector<int>(n,0)); int value = 1; // 左右边界 int l = 0, r = n - 1; // 上下边界 int t = 0, d = n - 1; int i = 0, j = 0;
while (value <= n * n) { for (; j <= r; j++) matrix[i][j] = value++; j--; i++; t++;
for (; i <= d; i++) matrix[i][j] = value++; i--; j--; r--;
vector<vector<int>> generateMatrix(int n) { vector<vector<int>> matrix(n, vector<int>(n,0)); int value = 1; int l = 0, r = n - 1; int t = 0, d = n - 1; int i = 0, j = 0;
// n为奇数时,无法遍历到中心,所以<=无法跳出循环 while (value < n * n) { for (; j < r; j++) matrix[i][j] = value++; t++;
for (const vector<int>& row: matrix) { for(int num: row) cout << num << " ";
cout << "\b\n"; }
return0; }
vector<vector<int>> generateMatrix(int n) { vector<vector<int>> matrix(n, vector<int>(n,0)); int value = 1; // 左右边界 int l = 0, r = n - 1; // 上下边界 int t = 0, d = n - 1; int i = 0, j = 0;
while (value < n * n) { for (; j < r; j++) matrix[i][j] = value++; t++;
int m = (int) matrix.size(); int n = (int) matrix[0].size();
int t = 0, d = m - 1; int l = 0, r = n - 1; int i = 0, j = 0;
// 这里用的size而非cnt,所以 m * n得减去1 while (nums.size() < m * n - 1) { // for中 nums.size() < m * n - 1 防止遍历到最后一个 for (; j < r && nums.size() < m * n - 1; j++) nums.push_back(matrix[i][j]); t++;
for (; i < d && nums.size() < m * n - 1; i++) nums.push_back(matrix[i][j]); r--;
for (; j > l && nums.size() < m * n - 1; j--) nums.push_back(matrix[i][j]); d--;
for (; i > t && nums.size() < m * n - 1; i--) nums.push_back(matrix[i][j]); l++; } // 补上最后一个 nums.push_back(matrix[i][j]);