刷leetcode hot100--矩阵6/1

1.螺旋矩阵【很久】6/1【感觉就是思路的搬运工,没完全理解】

54. 螺旋矩阵 - 力扣(LeetCode)

原来想

但是如果是奇数矩阵,遍历不到中间

解决思路:

用left,right,top,down标记/限定每次遍历的元素,每次从left到right......

记得在left、top更新后check是否符合情况,不符合直接break,防止多遍历

【LeetCode 每日一题】54. 螺旋矩阵 | 手写图解版思路 + 代码讲解_哔哩哔哩_bilibili

复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> res;
        int top = 0;
        int down = m-1;
        int left = 0;
        int right = n-1;
        while(left<=right && top<=down ){
            for(int i = left;i<=right;i++){
                res.push_back(matrix[top][i]);
                cout<<matrix[top][i]<<endl;
            }
            top++;
            for(int i = top;i<=down;i++){
                res.push_back(matrix[i][right]);
            }
            if(top<=down){
                right--;
            }else{
                break;
            }
            for(int i = right;i>=left;i--){
                res.push_back(matrix[down][i]);
            }
            if(left<=right){
                down--;
            }else{
                break;
            } 
            for(int i = down;i>=top;i--){
                res.push_back(matrix[i][left]);
            }
            left++;
            
        }
        return res;
    }
};
相关推荐
Nil20810 分钟前
leetcode 108有序数组转换为二叉搜索树
数据结构·算法·leetcode
高频因子挖掘机11 分钟前
QuantDash 成交量单位统一实战:从“手”到“股”的跨市场量化数据清洗全流程
后端·算法·github
Escalating_xu29 分钟前
【C++ STL简介】从六大组件到容器、迭代器与算法协作
java·c++·算法
纪念 2291 小时前
算法二叉树(一)
算法
liulilittle2 小时前
llmx 学习手册 06 —— CPU 指令集优化(AVX-512 三层演进)
c++·学习·算法·ai·llm
云登指纹浏览器2 小时前
做TikTok矩阵号用什么指纹浏览器?2026年实战横评
线性代数·矩阵
土司大王2 小时前
LeetCode hot100——相交链表
算法·leetcode·链表
土司大王2 小时前
LeetCode hot100——回文链表
算法·leetcode·链表
sel_93 小时前
【Docker】Docker 安装与使用详解:从零搭建到日常实战
人工智能·深度学习·算法·docker
小O的算法实验室11 小时前
IEEE TASE,基于MPC的多无人机协同搜索竞争群体优化方法
算法