题目
题目链接:https://leetcode.cn/problems/spiral-matrix-ii/
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
思路 & 代码
- 每条边的循环规则:左闭右开
- 每条边只遍历到倒数第二个节点,最后一个节点留给下一条边处理;
#include <vector>
#include <iostream>
using namespace std;class Solution {
public:vector<vector<int>> generateMatrix(int n) {int startx = 0, starty = 0;int offset = 1;int count = 1;int i,j;int loop = n/2;vector<vector<int>> res(n,vector<int>(n));while(loop--){i = startx;j = starty;for(j; j < n - offset; j++){res[i][j] = count++;}for(i; i < n-offset; i++){res[i][j] = count++;}for(; j > starty; j--){res[i][j] = count++;}for(; i > startx; i--){res[i][j] = count++;}startx++;starty++;offset++;}if(n % 2) {res[n/2][n/2] = count;}return res;}
};
// @lc code=endvoid printVector(vector<vector<int>>& nums){cout << "[";for(int i = 0; i < nums.size(); i++){if(i != 0) cout << " ";// 子数组之间加空格分隔cout << "[";for(int j = 0; j < nums[i].size(); j++){cout << nums[i][j];if(j != nums[i].size() - 1) cout << ", ";//每行的最后一个元素不加逗号}cout << "]";if(i != nums.size() - 1) cout << ",";// 最后一个子数组不加逗号}cout << "]" << endl;
}int main() {Solution obj;int n = 3;vector<vector<int>> res = obj.generateMatrix(n);printVector(res);}