自己写的
n>=2以上都适用,要单独对n=1写一个特例
变量过多,过于复杂
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> nums(n, vector<int>(n, 0)); int number = 0, F1_H=0,F1_L=0,F2_H=0,F2_L=n-1,F3_H=n-1,F3_L=n-1, F4_H = n-1, F4_L = 0; int flag = 0, length = n - 1; while (1) { if (n == 1) { nums[0][0] = 1; break; } if (number == (n * n))break; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << nums[i][j] << ' '; } cout << endl; } cout << "--------------------" << endl; if (flag == 0) { for (int i = 0; i < length; i++) { number++; nums[F1_H][F1_L+i] = number; } F1_H++; F1_L++; flag++; } else if (flag == 1) { for (int i = 0; i < length; i++) { number++; nums[F2_H+i][F2_L] = number; } F2_H++; F2_L--; flag++; } else if (flag == 2) { for (int i = 0; i < length; i++) { number++; nums[F3_H ][F3_L-i] = number; } F3_H--; F3_L--; flag++; } else if (flag == 3) { for (int i = 0; i < length; i++) { number++; nums[F4_H-i][F4_L ] = number; } F4_H--; F4_L++; flag=0; if (length == 2)length = 1; else length = length - 2; } } return nums; } }; int main() { int n = 1; Solution a; vector<vector<int>> res = a.generateMatrix(n ); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << res[i][j]<<' '; } cout << endl; } return 0; }
卡尔
原理类似
更加简洁
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> nums(n, vector<int>(n, 0)); int number = 1,start_X=0,start_Y=0 ; int flag = 0, length = 0; int loop = n / 2; int i = 0, j = 0; while (loop--) { i = start_X; j = start_Y; for ( j = start_Y; j < start_Y + n - length - 1; j++) nums[i][j] = number++; for ( i = start_X; i < start_X + n - length - 1; i++) nums[i][j] = number++; for (; j > start_Y ; j--) nums[i][j] = number++; for (; i > start_X ; i--) nums[i][j] = number++; start_X++; start_Y++; length += 2; for ( i = 0; i < n; i++) { for ( j = 0; j < n; j++) { cout << nums[i][j] << ' '; } cout << endl; } cout << "--------------------" << endl; } if (n % 2 == 1) nums[n / 2][n / 2] = number; return nums; } }; int main() { int n = 4; Solution a; vector<vector<int>> res = a.generateMatrix(n ); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << res[i][j]<<' '; } cout << endl; } return 0; }