LeetCode 54. Spiral Matrix

本文介绍了一种矩阵元素螺旋顺序遍历的方法,通过逐层旋转扫描的方式实现矩阵元素的收集。适用于仅一行或一列的特殊情况,并附带了完整的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.com/problems/spiral-matrix/

题目:

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

For example,
Given the following matrix:

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

You should return [1,2,3,6,9,8,7,4,5].

题解:

转圈取值。矩阵size 是 m*n, 第一行取值,从matrix[0][0]到matrix[0][n-2], 留下一个值为了接下来取最后一列的开始点,以此类推。

注意当只有一行或者一列时,要全部取值不能留下最后一个。

x代表当前row, y代表当前column.

走完一圈相当于走过两行,两列,所以m-=2, n-=2.

Time Complexity: O(m*n). Space: O(m*n).

AC Java:

 1 public class Solution {
 2     public List<Integer> spiralOrder(int[][] matrix) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
 5             return res;
 6         }
 7         int m = matrix.length;
 8         int n = matrix[0].length;
 9         int x = 0;
10         int y = 0;
11         while(m > 0 && n > 0){
12             if(m == 1){ //There is only one row
13                 for(int j = 0; j<n; j++){
14                     res.add(matrix[x][y++]);
15                 }
16                 break;
17             }
18             if(n == 1){ //There is only one column
19                 for(int i = 0; i<m; i++){
20                     res.add(matrix[x++][y]);
21                 }
22                 break;
23             }
24             
25             //旋转扫描
26             //首先,左到右
27             for(int j = 0; j<n-1; j++){
28                 res.add(matrix[x][y++]);
29             }
30             //上到下
31             for(int i = 0; i<m-1; i++){
32                 res.add(matrix[x++][y]);
33             }
34             //右到左
35             for(int j = 0; j<n-1; j++){
36                 res.add(matrix[x][y--]);
37             }
38             //下到上
39             for(int i = 0; i<m-1; i++){
40                 res.add(matrix[x--][y]);
41             }
42             x++;
43             y++;
44             m -= 2;
45             n -= 2;
46         }
47         return res;
48     }
49 }

 本题还有进阶版本Spiral Matrix II

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4839906.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值