码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Spiral Matrix

时间:2015-09-26 07:00:52      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/spiral-matrix/

转圈取值,上边从左到右,右边从上到下,下边从右到左,左边,从下到上。

若是矩阵size 是 m*n, 第一行取值,从matrix[0][0]到matrix[0][n-2], 留下一个值为了接下来取最后一列的开始点,以此方法递推。

当只有一行或者一列时,要全部取值不能留下最后一个。

x是代表第几row, 每次x++, y是代表第几column, 每次y++. 

从玩一圈相当于走过两行,两列,所以m-=2, n-=2.

AC Java:

 1 public class Solution {
 2     public List<Integer> spiralOrder(int[][] matrix) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
 5             return res;
 6         }
 7         int m = matrix.length;
 8         int n = matrix[0].length;
 9         int x = 0;
10         int y = 0;
11         
12         while(m>0 && n>0){
13             //There is only one row
14             if(m == 1){
15                 for(int i = 0; i<n; i++){
16                     res.add(matrix[x][y++]);
17                 }
18                 break;
19             }
20             //There is only one column
21             else if(n == 1){
22                 for(int i = 0; i<m; i++){
23                     res.add(matrix[x++][y]);
24                 }
25                 break;
26             }
27             
28             //Below is for circle
29             //Top, move right
30             for(int i = 0; i<n-1; i++){
31                 res.add(matrix[x][y++]);
32             }
33             
34             //Right, move down
35             for(int i = 0; i<m-1; i++){
36                 res.add(matrix[x++][y]);
37             }
38             
39             //Bottom, move left
40             for(int i = 0; i<n-1; i++){
41                 res.add(matrix[x][y--]);
42             }
43             
44             //Left, move up
45             for(int i = 0; i<m-1; i++){
46                 res.add(matrix[x--][y]);
47             }
48             
49             x++;
50             y++;
51             m-=2;
52             n-=2;
53         }
54         return res;
55     }
56 }

 本题还有进阶版本Spiral Matrix II

LeetCode Spiral Matrix

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4839906.html

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