码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Spiral Matrix

时间:2018-05-20 01:09:19      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:XA   arraylist   div   row   pre   etc   math   matrix   min   

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;
    }
}

 

LeetCode - Spiral Matrix

标签:XA   arraylist   div   row   pre   etc   math   matrix   min   

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/9062266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!