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)
    }
}
相关推荐
狗哥哥14 小时前
微前端路由设计方案 & 子应用管理保活
前端·架构
不知名XL14 小时前
day50 单调栈
数据结构·算法·leetcode
玄同76514 小时前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding
@––––––14 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
Yorlen_Zhang14 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
lxl130715 小时前
C++算法(1)双指针
开发语言·c++
xsyaaaan15 小时前
代码随想录Day31动态规划:1049最后一块石头的重量II_494目标和_474一和零
算法·动态规划
不绝19115 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
前端大卫15 小时前
Vue3 + Element-Plus 自定义虚拟表格滚动实现方案【附源码】
前端
无小道15 小时前
Qt-qrc机制简单介绍
开发语言·qt