Given a matrix of m x n elements (m rows, ncolumns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

这道题让我们搓一个螺旋丸,将一个矩阵按照螺旋顺序打印出来,只能一条边一条边的打印,首先要从给定的 mxn 的矩阵中算出按螺旋顺序有几个环,注意最中间的环可以是一个数字,也可以是一行或者一列。环数的计算公式是 min(m, n) / 2,知道了环数,就可以对每个环的边按顺序打印,比如对于题目中给的那个例子,个边生成的顺序是(用颜色标记了数字,Github 上可能无法显示颜色,请参见博客园上的帖子) Red -> Green -> Blue -> Yellow -> Black

1 2 3

 5 

7 8 

定义 p,q 为当前环的高度和宽度,当p或者q为1时,表示最后一个环只有一行或者一列,可以跳出循环。此题的难点在于下标的转换,如何正确的转换下标是解此题的关键,可以对照着上面的 3x3 的例子来完成下标的填写,代码如下:

解法一:

class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
if (matrix.empty() || matrix[].empty()) return {};
int m = matrix.size(), n = matrix[].size();
vector<int> res;
int c = m > n ? (n + ) / : (m + ) / ;
int p = m, q = n;
for (int i = ; i < c; ++i, p -= , q -= ) {
for (int col = i; col < i + q; ++col)
res.push_back(matrix[i][col]);
for (int row = i + ; row < i + p; ++row)
res.push_back(matrix[row][i + q - ]);
if (p == || q == ) break;
for (int col = i + q - ; col >= i; --col)
res.push_back(matrix[i + p - ][col]);
for (int row = i + p - ; row > i; --row)
res.push_back(matrix[row][i]);
}
return res;
}
};

如果觉得上面解法中的下标的转换比较难弄的话,也可以使用下面这种坐标稍稍简洁一些的方法。对于这种螺旋遍历的方法,重要的是要确定上下左右四条边的位置,那么初始化的时候,上边 up 就是0,下边 down 就是 m-1,左边 left 是0,右边 right 是 n-1。然后进行 while 循环,先遍历上边,将所有元素加入结果 res,然后上边下移一位,如果此时上边大于下边,说明此时已经遍历完成了,直接 break。同理对于下边,左边,右边,依次进行相对应的操作,这样就会使得坐标很有规律,并且不易出错,参见代码如下:

解法二:

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[].empty()) return {};
int m = matrix.size(), n = matrix[].size();
vector<int> res;
int up = , down = m - , left = , right = n - ;
while (true) {
for (int j = left; j <= right; ++j) res.push_back(matrix[up][j]);
if (++up > down) break;
for (int i = up; i <= down; ++i) res.push_back(matrix[i][right]);
if (--right < left) break;
for (int j = right; j >= left; --j) res.push_back(matrix[down][j]);
if (--down < up) break;
for (int i = down; i >= up; --i) res.push_back(matrix[i][left]);
if (++left > right) break;
}
return res;
}
};

若对上面解法中的多个变量还是晕的话,也可以使用类似迷宫遍历的方法,这里只要设定正确的遍历策略,还是可以按螺旋的方式走完整个矩阵的,起点就是(0,0)位置,但是方向数组一定要注意,不能随便写,开始时是要往右走,到了边界或者访问过的位置后,就往下,然后往左,再往上,所以 dirs 数组的顺序是 右->下->左->上,由于原数组中不会有0,所以就可以将访问过的位置标记为0,这样再判断新位置的时候,只要其越界了,或者是遇到0了,就表明此时需要转弯了,到 dirs 数组中去取转向的 offset,得到新位置,注意这里的 dirs 数组中取是按循环数组的方式来操作,加1然后对4取余,按照这种类似迷宫遍历的方法也可以螺旋遍历矩阵,参见代码如下:

解法三:

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[].empty()) return {};
int m = matrix.size(), n = matrix[].size(), idx = , i = , j = ;
vector<int> res;
vector<vector<int>> dirs{{, }, {, }, {, -}, {-, }};
for (int k = ; k < m * n; ++k) {
res.push_back(matrix[i][j]);
matrix[i][j] = ;
int x = i + dirs[idx][], y = j + dirs[idx][];
if (x < || x >= m || y < || y >= n || matrix[x][y] == ) {
idx = (idx + ) % ;
x = i + dirs[idx][];
y = j + dirs[idx][];
}
i = x;
j = y;
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/54

类似题目:

Spiral Matrix II

参考资料:

https://leetcode.com/problems/spiral-matrix/

https://leetcode.com/problems/spiral-matrix/discuss/20719/0ms-Clear-C%2B%2B-Solution

https://leetcode.com/problems/spiral-matrix/discuss/20599/Super-Simple-and-Easy-to-Understand-Solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Spiral Matrix 螺旋矩阵的更多相关文章

  1. [算法][LeetCode]Spiral Matrix——螺旋矩阵

    题目要求 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spir ...

  2. Leetcode 54:Spiral Matrix 螺旋矩阵

    54:Spiral Matrix 螺旋矩阵 Given a matrix of m x n elements (m rows, n columns), return all elements of t ...

  3. leetCode 54.Spiral Matrix(螺旋矩阵) 解题思路和方法

    Spiral Matrix Given a matrix of m x n elements (m rows, n columns), return all elements of the matri ...

  4. PAT甲级——1105 Spiral Matrix (螺旋矩阵)

    此文同步发布在CSDN:https://blog.csdn.net/weixin_44385565/article/details/90484058 1105 Spiral Matrix (25 分) ...

  5. [leetcode]54. Spiral Matrix螺旋矩阵

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or ...

  6. 【LeetCode】Spiral Matrix(螺旋矩阵)

    这是LeetCode里的第54道题. 题目要求: 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素. 示例 1: 输入: [ [ 1, 2, 3 ...

  7. 第29题:LeetCode54:Spiral Matrix螺旋矩阵

    给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素. 示例 1: 输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ...

  8. Leetcode54. Spiral Matrix螺旋矩阵

    给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素. 示例 1: 输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ...

  9. spiral matrix 螺旋矩阵

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or ...

随机推荐

  1. 关于join时显示no join predicate的那点事

    我们偶尔,非常偶尔的情况下会在一个查询计划中看到这样的警告: 大红叉,好吓人啊! 把鼠标放上去一看显示这样的信息 No join predicate 直译过来就是:没有连接谓词 在真实的生产环境下我们 ...

  2. 6.JAVA之GUI编程Action事件

    功能:单击一个按钮实现关闭窗口: import java.awt.*; import java.awt.event.*; public class StudyAction { // 定义该图形所需的组 ...

  3. go语言结构体

    定义: 是一种聚合的数据类型,是由零个或多个任意类型的值聚合成的实体. 成员: 每个值称为结构体的成员. 示例: 用结构体的经典案例处理公司的员工信息,每个员工信息包含一个唯一的员工编号.员工的名字. ...

  4. nginx简易教程

    概述 什么是nginx? Nginx (engine x) 是一款轻量级的Web 服务器 .反向代理服务器及电子邮件(IMAP/POP3)代理服务器. 什么是反向代理? 反向代理(Reverse Pr ...

  5. 微信小程序基础入门

    准备 Demo 项目地址 https://github.com/zce/weapp-demo Clone or Download(需准备GIT环境) $ cd path/to/project/root ...

  6. C++异常处理:try,catch,throw,finally的用法

    写在前面 所谓异常处理,即让一个程序运行时遇到自己无法处理的错误时抛出一个异常,希望调用者可以发现处理问题. 异常处理的基本思想是简化程序的错误代码,为程序键壮性提供一个标准检测机制. 也许我们已经使 ...

  7. 『.NET Core CLI工具文档』(六)dotnet 命令

    说明:本文是个人翻译文章,由于个人水平有限,有不对的地方请大家帮忙更正. 原文:dotnet command 翻译:dotnet 命令 名称 dotnet -- 运行命令行命令的一般驱动程序 概要 d ...

  8. DataGrid 列头实现国际化语言切换

    <DataGrid> <DataGrid.Columns> <DataGridTextColumn Binding="{x:Null}" Width= ...

  9. mysql主从之slave-skip-errors和sql_slave_skip_counter

    一般来说,为了保险起见,在主从库维护中,有时候需要跳过某个无法执行的命令,需要在slave处于stop状态下,执行 set global sql_slave_skip_counter=1以跳过命令.但 ...

  10. 301和302 Http状态有啥区别?

    301和302 Http状态有啥区别? 301,302 都是HTTP状态的编码,都代表着某个URL发生了转移,不同之处在于: 301 redirect: 301 代表永久性转移(Permanently ...