59. 螺旋矩阵 IIC++123456789101112131415161718192021class Solution {public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n, vector<int>(n, 0)); // 使用vector定义一个二维数组,全部元素初始化为零 int di[] = {0, 1, 0, -1}; int dj[] = {1, 0, -1, 0}; for(int i = 0, j = 0, d = 0, k = 1;k <= n * n;k++){ res[i][j] = k; int iNext = i + di[d]; int jNext = j + dj[d]; if(iNext < 0 || iNext >= n || jNext < 0 || jNext >= n || res[iNext][jNext]){ d = (d + 1) % 4; iNext = i + di[d]; jNext = j + dj[d]; } i = iNext; j = jNext; } return res; }}; 54. 螺旋矩阵C++