[LeetCode] Spiral Matrix

本文介绍了一种螺旋矩阵遍历算法,该算法可以按螺旋顺序返回矩阵中的所有元素。适用于不同大小和形状的矩阵,包括特殊情况如单行或单列矩阵。通过四个基本步骤:向右、向下、向左、向上进行遍历,并避免重复访问。

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

Spiral Matrix

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

Time Complexity
O(mn)

思路

We should think about these test cases :
if matrix == null, matrix.length == 0, matrix[0] == null, matrix[0].length == 0
if matrix just has one row
1 2 3

if matrix just has one column
1
2
3
if matrix is even
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

we're going to print it in this order
1 2 3 4
8 12 16
15 14 13
9 5
6 7
11
10

if matrix is odd
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18

print it in this order
1 2 3 4 5 6
12 18
17 16 15 14 13
7

if(rowStart > rowEnd || colStart > colEnd) break; it means it just have one row or one col left, so when it finish go right and go down. It should not do go left and go down anymore.

代码

public List<Integer> spiralOrder(int[][] matrix) {
    List<Integer> res = new ArrayList<Integer>();
    //corner case
    if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return res;
    int rows = matrix.length, cols = matrix[0].length;
    int rowStart = 0, colStart = 0, rowEnd = rows - 1, colEnd = cols - 1;
    
    while(rowStart <= rowEnd && colStart <= colEnd){
        //go right
        for(int i = colStart; i <= colEnd; i++){
            res.add(matrix[rowStart][i]);
        }
        rowStart++;
        //go down
        for(int i = rowStart; i <= rowEnd; i++){
            res.add(matrix[i][colEnd]);
        }
        colEnd--;
        
        if(rowStart > rowEnd || colStart > colEnd) break;
        
        //go left
        for(int i = colEnd; i >= colStart; i--){
            res.add(matrix[rowEnd][i]);
        }
        rowEnd--;
        
        //go up
        for(int i = rowEnd; i >= rowStart; i--){
            res.add(matrix[i][colStart]);
        }
        colStart++;
    }
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值