欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > LeetCode[中等] 54.螺旋矩阵

LeetCode[中等] 54.螺旋矩阵

2025/2/23 1:05:39 来源:https://blog.csdn.net/Theolulu/article/details/142375760  浏览:    关键词:LeetCode[中等] 54.螺旋矩阵

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

思路:定义方向数组,按照顺时针顺序:右(0,1),下(1,0),左(0,-1),上(0,-1)

  • 从矩阵的左上角开始遍历,并按照当前方向将元素加入结果列表order
  • 每次遍历后,检查下一个元素是否越界或已访问,如果是,则改变方向。
  • 最终,当遍历完成时,返回遍历顺序的列表。
public class Solution {public IList<int> SpiralOrder(int[][] matrix) {int[,] dir = {{0,1},{1,0}, {0,-1}, {-1,0}};List<int> order = new List<int>();int m = matrix.Length, n = matrix[0].Length;int total = m * n;int dirIndex = 0, row = 0, col = 0;bool[][] visited = new bool[m][];for(int i = 0; i < m; i++)visited[i] = new bool[n];for(int i = 0; i < total; i++){order.Add(matrix[row][col]);visited[row][col] = true;int nextRow = row + dir[dirIndex, 0], nextCol = col + dir[dirIndex, 1];if(nextRow < 0 || nextRow >= m || nextCol < 0 || nextCol >= n || visited[nextRow][nextCol])dirIndex = (dirIndex + 1) % 4;row += dir[dirIndex, 0];col += dir[dirIndex, 1];}return order;}
}

复杂度分析

  • 时间复杂度:O(m×n),其中 m 和 n 分别是矩阵 matrix 的行数和列数。需要遍历矩阵中的每个元素一次。
  • 空间复杂度:O(m×n),其中 m 和 n 分别是矩阵 matrix 的行数和列数。需要创建与矩阵相同大小的二维数组记录每个元素是否被访问过。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com