54.Spiral Matrix
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]
.
好久没做题了,博客也好久没更新,今天来一发水题,话说这题有点像poj的滑雪题.
传送门POJ:
题解:http://www.cnblogs.com/dick159/p/5258943.html
先说一下这题吧,就是分四个方向,然后从外到里按照顺序遍历,要注意结束条件.(我设置成访问过的值就不访问了)
ps:要判断一下间隔了的2个方向是否发生过移动,如果没有发生过移动则表示遍历已完毕.(这里我就用list的大小是否发生了变化来判断.)
目前没有想到更好的方法。【太笨了(╯﹏╰)】
Java Code:
public class Solution { public ListspiralOrder( int[][] matrix ) { List list = new ArrayList (); if( matrix == null || matrix.length == 0 ) return list; int m = matrix[ 0 ].length; int n = matrix.length; if( matrix[ 0 ].length == 1 ) { for( int i = 0; i < n; i++ ) { list.add( matrix[ i ][ 0 ] ); } return list; } if( matrix.length == 1 ) { for( int i = 0; i < m; i++ ) { list.add( matrix[ 0 ][ i ] ); } return list; } int l = 0; int preSize = 0; int i = -1; while( matrix[ l ][ l ] != -Integer.MAX_VALUE ) { preSize = list.size(); for( i = l; i < m - l; i++ ) { list.add( matrix[ l ][ i ] ); matrix[ l ][ i ] = -Integer.MAX_VALUE; } if(preSize == list.size()){ return list; } preSize = list.size(); for( i = l + 1; i < n - l; i++ ) { list.add( matrix[ i ][ m - l - 1 ] ); matrix[ i ][ m - l - 1 ] = -Integer.MAX_VALUE; } if(preSize == list.size()){ return list; } preSize = list.size(); for( i = m - l - 2; i >= l; i-- ) { list.add( matrix[ n - l - 1 ][ i ] ); matrix[ n - l - 1 ][ i ] = -Integer.MAX_VALUE; } if(preSize == list.size()){ return list; } preSize = list.size(); for( i = n - l - 2; i >= l + 1; i-- ) { list.add( matrix[ i ][ l ] ); matrix[ i ][ l ] = -Integer.MAX_VALUE; } l++; } return list; }}