LeetCode54 顺时针打印矩阵

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
被这题搞了心态,需要理清边界条件思路再开始code,不然越写越乱

public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new LinkedList<Integer>();
        if(matrix == null || matrix.length == 0) return res;
        int rows = matrix.length, cols = matrix[0].length;
        int start = 0;
        while(rows > start * 2 && cols > start * 2){
            printOneCircle(matrix,start,rows,cols,res);
            start ++;
        }
        return res;
    }
    public void printOneCircle(int[][] matrix, int start, int rows, int cols,List<Integer> res){
        int endX = cols - 1 - start;
        int endY = rows - 1 - start;
        for(int i = start; i <= endX; i++){
            res.add(matrix[start][i]);
        }
        if(endY > start){
            for(int i = start+1; i <= endY; i++){
                res.add(matrix[i][endX]);
            }
        }
        if(endY > start && endX > start){
            for(int i = endX - 1; i >= start; i--){
                res.add(matrix[endY][i]);
            }
        }
        if(endY > start + 1 && endX > start){
            for(int i = endY - 1; i > start; i--){
                res.add(matrix[i][start]);
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/84924966