码迷,mamicode.com
首页 > 编程语言 > 详细

Spiral Matrix leetcode java

时间:2014-08-03 05:24:09      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   java   strong   for   ar   

题目

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].

 

题解
这道题是实现题。

考虑2个初始条件,如果矩阵只有一行或者一列,那么无需转圈,依次输出即可。

其他情况均需转圈:从左到右,从上到下,从右到左,从下到上。 从大圈依次循环到小圈即可。

 

代码如下:

 

 1    public ArrayList<Integer> spiralOrder(int[][] matrix) {
 2         ArrayList<Integer> result = new ArrayList<Integer>();
 3         if(matrix == null || matrix.length == 0)
 4             return result;
 5  
 6         int m = matrix.length;
 7         int n = matrix[0].length;
 8  
 9         int x=0; 
10         int y=0;
11  
12         while(m>0 && n>0){
13  
14             //if one row/column left, no circle can be formed
15             if(m==1){
16                 for(int i=0; i<n; i++){
17                     result.add(matrix[x][y++]);
18                 }
19                 break;
20             }else if(n==1){
21                 for(int i=0; i<m; i++){
22                     result.add(matrix[x++][y]);
23                 }
24                 break;
25             }
26  
27             //below, process a circle
28  
29             //top - move right
30             for(int i=0;i<n-1;i++)
31                 result.add(matrix[x][y++]);
32  
33             //right - move down
34             for(int i=0;i<m-1;i++)
35                 result.add(matrix[x++][y]);
36  
37             //bottom - move left
38             for(int i=0;i<n-1;i++)
39                 result.add(matrix[x][y--]);
40  
41             //left - move up
42             for(int i=0;i<m-1;i++)
43                 result.add(matrix[x--][y]);
44  
45             x++;
46             y++;
47             m=m-2;
48             n=n-2;
49         }
50  
51         return result;
52     }

Reference:http://www.programcreek.com/2013/01/leetcode-spiral-matrix-java/

Spiral Matrix leetcode java,布布扣,bubuko.com

Spiral Matrix leetcode java

标签:style   blog   http   color   java   strong   for   ar   

原文地址:http://www.cnblogs.com/springfor/p/3887890.html

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