当前位置: 代码迷 >> 综合 >> [LeetCode] 旋转矩阵 II
  详细解决方案

[LeetCode] 旋转矩阵 II

热度:48   发布时间:2024-01-24 16:16:56.0

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

解:完全模拟过程,注意好上下左右四个边界就好

class Solution {
public:vector<vector<int>> generateMatrix(int n) {vector<vector<int>> res(n, vector<int>(n)); for(int s = 0,e = n-1,m = 1;s <= e;s++,e--){//左到右for(int j = s;j <= e;j++)res[s][j] = m++;//上到下for(int i = s+1;i <= e;i++)res[i][e] = m++;//右到左for(int j = e- 1;j >= s;j-- )res[e][j] = m++;//下到上for(int i = e - 1;i >= s+1;i--)res[i][s] = m++;}return res;}
};