1. 程式人生 > >LeetCode54 順時針列印矩陣

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]);
            }
        }
    }