首页 > 其他 > 详细

Spiral Matrix

时间:2014-02-10 17:06:07      阅读:331      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
 1 public class Solution {
 2     public ArrayList<Integer> spiralOrder(int[][] matrix) {
 3         int row = matrix.length;
 4         ArrayList<Integer> res = new ArrayList<Integer> ();
 5         if(row<=0) return res;
 6         int col = matrix[0].length;
 7         int start = 0;
 8         while(start*2<row && start*2<col){
 9             print(matrix,start,res);
10             start++;
11         }
12         return res;
13     }
14     public void print(int[][] matrix,int start, ArrayList<Integer>res){
15         int endX = matrix[0].length-1-start;
16         int endY = matrix.length-1-start;
17         
18         //print up
19         for(int i=start;i<=endX;i++){
20             res.add(matrix[start][i]);
21         }
22         //print right
23         for(int i=start+1;i<=endY;i++){
24             res.add(matrix[i][endX]);
25         }
26         //print down
27         if(endY>start){
28             for(int i=endX-1;i>=start;i--){
29                 res.add(matrix[endY][i]);
30             }
31         }
32         //print left
33         if(endX>start){
34             for(int i=endY-1;i>start;i--){
35                 res.add(matrix[i][start]);
36             }
37         }
38     }
39 }
View Code

Spiral Matrix

原文:http://www.cnblogs.com/krunning/p/3542967.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!