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]
.
这道题想了好久没想起来,只能是怪自己太懒,懒得去思考去尝试,应该静下心来不能太浮躁。
这里分四种情况,从左到右,从上到下,从右向左,从下向上。
仔细观察发现刚好可以利用rowResult和columnResult的变化来做。
下面将代码放上,一定要注意,在
int row = matrix.length;
int column = matrix[0].length;之前判断如果矩阵为空的情况。这样column才不会出错。代码如下:
public class Solution { public ListspiralOrder(int[][] matrix) { List listResult = new ArrayList (); if(matrix == null || matrix.length==0){ return listResult; } int row = matrix.length; int column = matrix[0].length; int rowNumber = 0; int columnNumber = 0; while(row>0&&column>0){ if(row == 1){ for(int i = 0;i