zoukankan      html  css  js  c++  java
  • [LeetCode] 59. 螺旋矩阵 II

    [LeetCode] 59. 螺旋矩阵 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]]

    思路

    1. 模拟

    2. 按层模拟(一层一层的填)

    相似题目:54. 螺旋矩阵

    代码

    用模拟写的,按层模拟见官方题解https://leetcode-cn.com/problems/spiral-matrix-ii/solution/luo-xuan-ju-zhen-ii-by-leetcode-solution-f7fp/

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            int mni = 0, mxi = n - 1;
            int mnj = 0, mxj = n - 1;
            int i = 0, j = 0, di = 0, dj = 1;
            vector<vector<int>> ans;
            ans.resize(n);
            for (int i = 0; i < n; i++) {
                ans[i].resize(n);
            }
            int cur = 1;
            while(mni <= mxi && mnj <= mxj) {
                ans[i][j] = cur++;
                if (di == -1 && i == mni && j == mnj) {
                    di = 0;
                    dj = 1;
                    mnj++;
                } else if (dj == 1 && i == mni && j == mxj) {
                    di = 1;
                    dj = 0;
                    mni++;
                } else if (di == 1 && i == mxi && j == mxj) {
                    di = 0;
                    dj = -1;
                    mxj--;
                } else if (dj == -1 && i == mxi && j == mnj) {
                    di = -1;
                    dj = 0;
                    mxi--;
                }
                i += di;
                j += dj;
            }
            return ans;
        }
    };
    
    
    欢迎转载,转载请注明出处!
  • 相关阅读:
    CSRF
    PHP XXE漏洞
    jumpserver安装与部署
    ELK
    docker pull下来的镜像放哪儿了?
    MobSF 框架安装使用部署
    加密流量分析
    Pόlya定理-学习笔记
    所有区间异或的和的 一个加强
    计算一个序列有多少个不同的01子序列
  • 原文地址:https://www.cnblogs.com/huihao/p/15425142.html
Copyright © 2011-2022 走看看