54. Spiral Matrix

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res=new ArrayList<Integer>();
        if(matrix.length==0||matrix[0].length==0)
            return res;
        spiralOrder(0, 0, matrix.length-1, matrix[0].length-1, res, matrix);
        return res;
    }
    private void spiralOrder(int top, int left, int bottom, int right, List<Integer> res, int[][] matrix)
    {
        if(top>bottom||left>right)
            return;
        for(int k=left;k<=right;k++)
            res.add(matrix[top][k]);
        for(int k=top+1;k<=bottom;k++)
            res.add(matrix[k][right]);
        if(top!=bottom)
            for(int k=right-1;k>=left;k--)
                res.add(matrix[bottom][k]);
        if(left!=right)
            for(int k=bottom-1;k>top;k--)
                res.add(matrix[k][left]);
        spiralOrder(top+1, left+1, bottom-1, right-1, res, matrix);
    }
}

 

posted @ 2017-09-26 01:44  Weiyu Wang  阅读(126)  评论(0编辑  收藏  举报