当前位置: 代码迷 >> 综合 >> LeetCode 59. 螺旋矩阵 II(python、c++)
  详细解决方案

LeetCode 59. 螺旋矩阵 II(python、c++)

热度:43   发布时间:2024-03-10 01:20:33.0

题目描述

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

题解
(循环) O(n2)
我们顺时针定义四个方向:上右下左。
从左上角开始遍历,先往右走,走到不能走为止,然后更改到下个方向,再走到不能走为止,依次类推,遍历 n^2 个格子后停止。
时间复杂度分析:矩阵中每个格子遍历一次,所以总时间复杂度是 O(n2)。

c++版

class Solution {
    
public:vector<vector<int>> generateMatrix(int n) {
    vector<vector<int>> ans;ans = vector<vector<int>> (n, vector<int> (n));int x = 0, y = 0;int step = 1;while(step <= n*n){
    while(y < n && !ans[x][y])ans[x][y++] = step++;y-=1;x+=1;while(x < n && !ans[x][y]) ans[x++][y] = step++;x-=1;y-=1;while(y >= 0 &&!ans[x][y]) ans[x][y--] = step++;y += 1;x-=1;while(x >= 0 && !ans[x][y]) ans[x--][y] = step++;x+=1;y+=1;}return ans;}
};

python版

class Solution:def generateMatrix(self, n: int) -> List[List[int]]:ans = [[0 for _ in range(n)] for _ in range(n)]x = 0y = 0step = 1while step <= n*n:while y < n and ans[x][y] == 0:ans[x][y] = step;y += 1step += 1y-=1;x+=1;while x < n and ans[x][y] == 0:ans[x][y] = step;x += 1step += 1x-=1;y-=1;while y >= 0 and ans[x][y] == 0:ans[x][y] = step;y -= 1step += 1y += 1;x-=1;while x >= 0 and ans[x][y] == 0:ans[x][y] = step;x -= 1step += 1x+=1;y+=1;return ans