首页 > 其他 > 详细

[Leetcode]-- Spiral Matrix

时间:2014-02-11 18:48:23      阅读:371      评论: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,布布扣
public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        int rows = matrix.length;
        if(rows == 0){
            return result;
        }
        int cols = matrix[0].length;
        if(cols == 0)
            return result;
            
        int start = 0;
        while(rows > start * 2 && cols > start * 2){
            printCircle(matrix, rows, cols, start, result);
            start ++;
        }
        return result;
    }
    
    public void printCircle(int[][] matrix, int rows, int cols, int start, ArrayList<Integer> result){
        int endX = cols - 1 - start;
        int endY = rows - 1 - start;
        
        // print up
        for(int i = start; i <= endX; i++){
            result.add(matrix[start][i]);
        }
        
        // print right
        if(endY > start){
            for(int i = start + 1; i <= endY; i ++){
                result.add(matrix[i][endX]);
            }
        }
        // print down
        if(endX > start && endY > start){
            for(int i = endX - 1; i >= start; i--){
                result.add(matrix[endY][i]);
            }
        }
        // print left 转到最左边的时候 高度又减少了1,因为被下面的那一行多占了1
        if(endX > start && endY - 1 > start){
            for(int i = endY - 1; i > start; i--){
                result.add(matrix[i][start]);
            }
        }
    }
}
bubuko.com,布布扣

[Leetcode]-- Spiral Matrix

原文:http://www.cnblogs.com/RazerLu/p/3544280.html

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