54. 螺旋矩阵【rust题解】

题目

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例

示例 1

输入:matrix = \[1,2,3,4,5,6,7,8,9]

输出:1,2,3,6,9,8,7,4,5

示例 2

输入:matrix = \[1,2,3,4,5,6,7,8,9,10,11,12]

输出:1,2,3,4,8,12,11,10,9,5,6,7

提示

php 复制代码
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

思路

深搜,方向旋转。需要特别处理在最左边往上搜索的情况。

AC代码

rust 复制代码
impl Solution {
    pub fn dfs(v: &Vec<Vec<i32>>, vis: &mut Vec<Vec<bool>>, x: i32, y: i32) -> Vec<i32> {
        let x_len = v.len() as i32;
        let y_len = v[0].len() as i32;
        let mut res: Vec<i32> = Vec::new();
        if x < 0 || x >= x_len || y < 0 || y >= y_len || vis[x as usize][y as usize] {
            return res;
        }
        vis[x as usize][y as usize] = true;
        let mut res1: Vec<i32> = Vec::new();
        let mut res2: Vec<i32> = Vec::new();
        let mut res3: Vec<i32> = Vec::new();
        let mut res4: Vec<i32> = Vec::new();
        res1 = match x >= 1 && (y == 0 || (y >= 1 && vis[x as usize][y as usize - 1])) && !vis[x as usize - 1][y as usize]{
            true => Solution::dfs(v, vis, x - 1, y),
            _ => Solution::dfs(v, vis, x, y + 1)
        };
        res2 = Solution::dfs(v, vis, x + 1, y);
        res3 = Solution::dfs(v, vis, x, y - 1);
        res4 = Solution::dfs(v, vis, x - 1, y);
        res.push(v[x as usize][y as usize]);
        res.extend(res1);
        res.extend(res2);
        res.extend(res3);
        res.extend(res4);
        res
    }

    pub fn spiral_order(v: Vec<Vec<i32>>) -> Vec<i32> {
        let x_len = v.len();
        let y_len = v[0].len();
        let mut vis: Vec<Vec<bool>> = vec![vec![false; y_len]; x_len];
        Solution::dfs(&v, &mut vis, 0 , 0)
    }
}
相关推荐
土司大王2 分钟前
LeetCode hot100——合并两个有序链表
算法·leetcode·链表
码行山野赴时序归途5 分钟前
算法效率的度量(上):时间复杂度中的对数思维
c语言·数据结构·算法
16月6日-晴9 分钟前
Java面向对象进阶—多态
java·开发语言
kyriewen11 分钟前
我带着DeepSeek Harness跑了一周真实需求——这份避坑速查表请收好
前端·ai编程·deepseek
计算机魔术师16 分钟前
OpenAI不单独发o3了,Altman说GPT-5才是终局
前端
冯汉栩37 分钟前
Swift Control RollingCountdownView(动画倒计时)
开发语言·ios·swift
lisanmengmeng40 分钟前
搭建elk环境并接入frostmourne,实现监控报警效果(五)
开发语言·elk·日志·日志监控
算AI1 小时前
基于LLM的无人机仿真测试:新方法竞赛夺佳绩
人工智能·深度学习·算法·机器学习·ai
一座古城1 小时前
Claude Code 架构源码解析:AI 应用开发的范式跃迁
前端·后端
K哥爬虫1 小时前
【JS 逆向百例】Vaptcha V4 手势验证码逆向分析
前端·后端