栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【数据结构基础

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构基础

原题连接: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> generateMatrix(int n) {
        // maxn最大值 cur当前值
        int maxn = n * n, cur = 1;

        // 方向: 右下左上
        vector> direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        vector> ans(n, vector(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),常数个临时变量
暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1015470.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号