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

54. Spiral Matrix

时间:2017-07-17 20:16:01      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:lis   get   ase   should   win   list   targe   color   html   

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

难度:87,这道题跟 Rotate Image 很相似,都是需要把矩阵分割成层来处理,每一层都是按:1. 正上方;2. 正右方;3. 正下方;4. 正左方这种顺序添加元素到结果集合。实现中要注意两个细节,一个是因为题目中没有说明矩阵是不是方阵,因此要先判断一下行数和列数来确定螺旋的层数,mina(行, 列) /2才是螺旋数。二是有可能存在这种情况比如:3*4矩阵,螺旋只有一层,但中间还有一行元素没有没加入。所以最后要将剩余的走完。

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (matrix==null || matrix.length==0 || matrix[0].length==0) return res;
        int Min = Math.min(matrix.length, matrix[0].length);
        int levelMax = Min / 2;
        for (int level=0; level<levelMax; level++) {
            for (int i=level; i<matrix[0].length-1-level; i++) {
                res.add(matrix[level][i]);
            }
            for (int i=level; i<matrix.length-1-level; i++) {
                res.add(matrix[i][matrix[0].length-1-level]);
            }
            for (int i=matrix[0].length-1-level; i>level; i--) {
                res.add(matrix[matrix.length-1-level][i]);
            }
            for (int i=matrix.length-1-level; i>level; i--) {
                res.add(matrix[i][level]);
            }
        }
        if (Min % 2 == 1) {
            if (matrix.length < matrix[0].length) {
                for (int i=levelMax; i<matrix[0].length-levelMax; i++) {
                    res.add(matrix[levelMax][i]);
                }
            }
            else {
                for (int i=levelMax; i<matrix.length-levelMax; i++) {
                    res.add(matrix[i][levelMax]);
                }
            }
        }
        return res;
    }
}

 这种题就得画图, 然后看看遍历顺序

然后就是得分情况讨论, 记住coner case

54. Spiral Matrix

标签:lis   get   ase   should   win   list   targe   color   html   

原文地址:http://www.cnblogs.com/apanda009/p/7197016.html

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