LeetCode - Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), 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]






复杂度

时间 O(NM) 空间 O(1)

思路

首先考虑最简单的情况,如图我们先找最外面这圈X,这种情况下我们是第一行找前4个,最后一列找前4个,最后一行找后4个,第一列找后4个,这里我们可以发现,第一行和最后一行,第一列和最后一列都是有对应关系的。即对i行,其对应行是m - i - 1,对于第j列,其对应的最后一列是n - j - 1

XXXXX
XOOOX
XOOOX
XOOOX
XXXXX

然后进入到里面那一圈,同样的顺序没什么问题,然而关键在于下图这么两种情况,一圈已经没有四条边了,所以我们要单独处理,只加那唯一的一行或一列。另外,根据下图我们可以发现,圈数是宽和高中较小的那个,加1再除以2。

OOOOO  OOO
OXXXO  OXO
OOOOO  OXO
       OXO
       OOO


class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        
        int m = matrix.length;//rows
        if(m == 0){
            return res;
        }
        int n = matrix[0].length;//columns
        //total rounds can be calculatd by using this
        int rounds = (Math.min(m,n)+1)/2;
        
        for(int i=0; i<rounds; i++){
            //corresponding row
            int cRow = m-i-1;
            //corresponding column
            int cColumn = n-i-1;
            //corresponding row equals current row
            if(i == cRow){
                for(int j=i; j<=cColumn; j++){
                    res.add(matrix[i][j]);
                }
            }
            //corresponding column equals current column
            else if(i == cColumn){
                for(int j=i; j<=cRow; j++){
                    res.add(matrix[j][i]);
                }
            }
            //normal case
            else{
                //first row
                for(int j=i; j<cColumn; j++){
                    res.add(matrix[i][j]);
                }
                //last column
                for(int j=i; j<cRow; j++){
                    res.add(matrix[j][cColumn]);
                }
                //last row
                for(int j=cColumn; j>i; j--){
                    res.add(matrix[cRow][j]);
                }
                //first column
                for(int j=cRow; j>i; j--){
                    res.add(matrix[j][i]);
                }
            }
            
        }
        return res;
    }
}

 

转载于:https://www.cnblogs.com/incrediblechangshuo/p/9062266.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值