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)
    }
}
相关推荐
爱吃山竹的大肚肚几秒前
在Java中,从List A中找出List B没有的数据(即求差集)
开发语言·windows·python
weixin_462446232 分钟前
【原创实践】Python 将 Markdown 文件转换为 Word(docx)完整实现
开发语言·python·word
企微自动化5 分钟前
企业微信二次开发:深度解析外部群主动推送的实现路径
java·开发语言·企业微信
elangyipi1238 分钟前
前端面试题:如何减少页面重绘跟重排
前端·面试·html
我的offer在哪里12 分钟前
c++的回调函数
开发语言·c++
爱学大树锯12 分钟前
592 · 查找和替换模式
算法
一棵开花的树,枝芽无限靠近你14 分钟前
【face-api.js】2️⃣ NetInput - 神经网络输入封装类
开发语言·javascript·神经网络
想学后端的前端工程师15 分钟前
【前端安全防护实战指南:从XSS到CSRF全面防御】
前端·安全·xss
yongche_shi15 分钟前
第九十九篇:Python在其他领域的应用:游戏开发、物联网、AIoT简介
开发语言·python·物联网·游戏开发·aiot
froginwe1116 分钟前
Node.js 回调函数
开发语言