Leetcode 59. Spiral Matrix II | | Leetcode 59. Spiral Matrix II 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution123456789101112131415161718192021222324252627282930313233class Solution {public: vector<vector<int>> generateMatrix(int n) { int total = n * n; vector<vector<int>> matrix; for(int i = 0; i < n; i++) { vector<int> row(n, 0); matrix.push_back(row); } for(int i = 0, j = 0, count = 0; count < total; i++, j++) { // top for(int k = j; k < n - j; k++) { matrix[i][k] = ++count; } // right for(int k = i + 1; k < n - i; k++) { matrix[k][n - 1 - j] = ++count; } // bottom for(int k = n - 2 - j; k >= j; k--) { matrix[n - 1 - i][k] = ++count; } // left for(int k = n - 2 - i; k > i; k--) { matrix[k][j] = ++count; } } return matrix; }}; Reference https://leetcode.com/problems/spiral-matrix-ii/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏