【数据结构基础_数组】Leetcode 59. 螺旋矩阵 II

原题连接:Leetcode 59. Spiral Matrix II

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

Example 1:
在这里插入图片描述

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

Example 2:

Input: n = 1
Output: [[1]]

Constraints:

  • 1 <= n <= 20

方法一:模拟

思路:

模拟呗,设置四个方向
每次判断下一格是否越界,越界就转向

c++代码:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        // maxn最大值 cur当前值
        int maxn = n * n, cur = 1;

        // 方向: 右下左上
        vector<vector<int>> direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        vector<vector<int>> ans(n, vector<int>(n));

        // xy坐标 i方向的下标
        int x = 0, y = 0, i = 0;;

        while(cur <= maxn){
            ans[x][y] = cur;
            cur++;

            // 若果下一个方向越界 或者碰到了已经填过数的格子 将方向转向
            int next_x = x + direction[i][0], next_y = y + direction[i][1];
            if(next_x < 0 || next_x >= n || next_y < 0 || next_y >= n || ans[next_x][next_y] != 0){
                i = (i + 1) % 4;
            }

            x = x + direction[i][0];
            y = y + direction[i][1];
        }

        return ans;
    }
};

复杂度分析:

  • 时间复杂度:O(n2),循环进行n2
  • 空间复杂度:O(1),常数个临时变量
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值