Vison's Blog
所有文章
文章总览
编辑器
Publications
About Me
Search
目录
#toc-container
下载Markdown文件
【3.15】LeetCode每日一题· 螺旋矩阵
2021年03月15日 10时07分
标签:
LeetCode
数组
## 题目描述 给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。 #### 示例1 [](https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg "示例") 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5] #### 示例2 [](https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg "示例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] #### 提示 m == matrix.length n == matrix[i].length 1 <= m, n <= 10 -100 <= matrix[i][j] <= 100 #### 来源 > 来源:力扣(LeetCode) > 链接:[题目链接](https://leetcode-cn.com/problems/spiral-matrix/ "题目链接") ## 解题思路 设置一个变量`direct`指示当前前进方向,当向该方向走下一步时如果**数组越界**或者**已走过**,就换一个方向。对每一个走过的方格,可以将其中的数字置为一个不在输入范围内的数字,表示该方格已走过。模拟即可。 ## 代码 class Solution { public: vector
spiralOrder(vector
>& matrix) { vector
res; const int N = matrix.size(), M = matrix[0].size(); int i = 0, j = 0, cnt = 0; int direct = 0; while(cnt < N*M){ cnt++; res.push_back(matrix[i][j]); matrix[i][j] = -INT_MAX; switch(direct){ case(0):{ if(j+1 >= M || matrix[i][j+1] == -INT_MAX){ direct++; i++; }else{ j++; } break; } case(1):{ if(i+1 >= N || matrix[i+1][j] == -INT_MAX){ direct++; j--; }else{ i++; } break; } case(2):{ if(j-1 < 0 || matrix[i][j-1] == -INT_MAX){ direct++; i--; }else{ j--; } break; } case(3):{ if(i-1 < 0 || matrix[i-1][j] == -INT_MAX){ direct = 0; j++; }else{ i--; } break; } } } return res; } }; ### 用时和内存 > 执行用时:0 ms,在所有 C\++提交中击败了100.00%的用户 > 内存消耗:6.5 MB,在所有 C\++提交中击败了94.95%的用户
所有评论
暂无评论
新增评论
评论
邮箱
邮箱仅作验证使用
图形验证码
邮箱验证码
发送验证码
发表评论
所有评论
暂无评论