54. Spiral Matrix
2022/2/4 6:12:31
本文主要是介绍54. Spiral Matrix,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
This is an exactly same problem with "59. Spiral Matrix II". I set every direction as a status, when one direction was implemented, the current status turns to the next status.
Which different status, the scan direction is different, but all scans cannot exceed the edges of the matrix.
The time complexity is O(m*n):
public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return res; int m = matrix.length; int n = matrix[0].length; int top = 0, bottom = m - 1, left = 0, right = n - 1; int status = 0; //we set every directions as a status, there are toally 4 status. while (top <= bottom && left <= right) { if (status % 4 == 0) { //the first direction, from left to right for (int j = left; j <= right; j++) { res.add(matrix[top][j]); } top++; } else if (status % 4 == 1) { //the second direction, from top to bottom for (int i = top; i <= bottom; i++) { res.add(matrix[i][right]); } right--; } else if (status % 4 == 2) { //the third direction, from right to left for (int j = right; j >= left; j--) { res.add(matrix[bottom][j]); } bottom--; } else if (status % 4 == 3) { //the fourth direction, from bottom to top for (int i = bottom; i >= top; i--) { res.add(matrix[i][left]); } left++; } } return res; }
这篇关于54. Spiral Matrix的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-27数据结构与算法面试题详解及练习
- 2024-12-27网络请求面试题详解与实战
- 2024-12-27数据结构和算法面试真题详解与实战教程
- 2024-12-27网络请求面试真题解析与实战教程
- 2024-12-27数据结构和算法大厂面试真题详解与实战指南
- 2024-12-27TS大厂面试真题解析与应对策略
- 2024-12-27TS大厂面试真题详解与解析
- 2024-12-27网站安全入门:如何识别和修复漏洞
- 2024-12-27SQL注入基础教程
- 2024-12-27初学者指南:理解和修复跨域漏洞