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

54. Spiral Matrix

时间:2016-11-27 16:58:20      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:nbsp   bottom   row   public   length   []   follow   spi   code   

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

 

直接travel

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> array = new ArrayList<>();
        if(matrix.length == 0) return array;
        int rowtop = 0;
        int rowbottom = matrix.length-1;
        int colleft = 0;
        int colright = matrix[0].length-1;
        while(rowtop <= rowbottom && colleft <= colright){
            //travel from left to right
            for(int i = colleft ; i <= colright ; i++){
                array.add(matrix[rowtop][i]);
            }
            rowtop++;
            
            // travel from top to bottom
            for(int i = rowtop ; i <= rowbottom ; i++){
                array.add(matrix[i][colright]);
            }
            colright--;
            
            //travel from right to left
            if(rowbottom >= rowtop)
                for(int i = colright ; i >= colleft ; i--){
                    array.add(matrix[rowbottom][i]);
                }
            rowbottom--;
            
            // travel from bottom to top
            if(colleft <= colright)
                for(int i = rowbottom ; i >= rowtop ; i--){
                    array.add(matrix[i][colleft]);
                }
            colleft++;
            
        }
        return array;
    }
}

 

54. Spiral Matrix

标签:nbsp   bottom   row   public   length   []   follow   spi   code   

原文地址:http://www.cnblogs.com/joannacode/p/6106403.html

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