• 【每日一题】对角线遍历


    文章目录

    在这里插入图片描述

    题目描述


    498. 对角线遍历
    给你一个大小为 m x n 的矩阵 mat ,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素。

    示例 1:

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

    输入:mat = [[1,2],[3,4]]
    输出:[1,2,3,4]

    提示:

    m == mat.length
    n == mat[i].length
    1 <= m, n <= 104
    1 <= m * n <= 104
    -105 <= mat[i][j] <= 105

    题解


    类似之前发的每日一题之字形打印二叉树,从数组的左上角看,实际上也是一颗二叉树形状,这题遍历的时候需要注意由于访问下,右有可能访问到同一个节点,所以需要创建visited数组。

    解法的不足:

    • 用到了O(N^2)的visited矩阵,但是这没有办法避免,对原数组做标记不可取。
    • deque的数据不能直接转移到vector上。
    class Solution {
    public:
        int a[2][2] = {{1,0},{0,1}};
        vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
            queue<pair<int,int>> q;
            q.push({0,0});
            vector<vector<bool>> visited(mat.size(),vector<bool>(mat[0].size(),false));
            vector<int> res;
            bool flag =  true;
            res.push_back(mat[0][0]);
            while(!q.empty())
            {
                int sz = q.size();
                deque<int> dq;
                while(sz -- )
                {
                    pair<int,int> p = q.front();
                    q.pop();
                    for(int i = 0;i < 2;++i)
                    {
                        int newx = p.first + a[i][0];//下 , 右
                        int newy = p.second + a[i][1];
                        if(newx < mat.size() && newy < mat[0].size() && visited[newx][newy] == false)
                        {
                            q.push({newx,newy});
                            dq.push_back(mat[newx][newy]);
                            visited[newx][newy] = true;
                        }
                    }
                }
                if(flag)
                {
                    res.insert(res.end(),dq.rbegin(),dq.rend());
                }
                else
                {
                    res.insert(res.end(),dq.begin(),dq.end());
                }
                flag = !flag;  
            }
            return res;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43



    end

    • 喜欢就收藏
    • 认同就点赞
    • 支持就关注
    • 疑问就评论
  • 相关阅读:
    关于看病报销额度
    基于STM32设计的小龙虾养殖系统(带手机APP)
    6 个问题搞懂 HTTPS 加密通信的原理与 HTTPS 通信安全协议
    怎么找通达信行情接口c++源码?
    你知道嵌入式开发主要做什么吗?
    Altium Designer学习笔记7
    GROUBI
    【测试】SonarLint连接SonarQube服务扫描
    105AspectRatio调整宽高比组件_flutter
    详细介绍BERT模型
  • 原文地址:https://blog.csdn.net/weixin_52344401/article/details/126550393