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
。
XXXXXXOOOXXOOOXXOOOXXXXXX
然后进入到里面那一圈,同样的顺序没什么问题,然而关键在于下图这么两种情况,一圈已经没有四条边了,所以我们要单独处理,只加那唯一的一行或一列。另外,根据下图我们可以发现,圈数是宽和高中较小的那个,加1再除以2。
OOOOO OOOOXXXO OXOOOOOO OXO OXO OOO
class Solution { public ListspiralOrder(int[][] matrix) { List 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 i; j--){ res.add(matrix[cRow][j]); } //first column for(int j=cRow; j>i; j--){ res.add(matrix[j][i]); } } } return res; }}