LeetCode : 54. Spiral Matrix 顺时针打印矩阵

试题
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]
代码
顺时针打印即可

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> out = new ArrayList<>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return out;
        }
        
        int row2 = matrix.length - 1;
        int col2 = matrix[0].length - 1;
        int row1 = 0, col1 = 0;
        while(row1 <= row2 && col1 <= col2){
            for(int i = col1; i <= col2; i++){
                out.add(matrix[row1][i]);
            }
            for(int i = row1 + 1; i <= row2; i++){
                out.add(matrix[i][col2]);
            }
            if(row1 < row2 && col1 < col2){
                for(int i = col2 - 1; i >= col1; i--){
                    out.add(matrix[row2][i]);
                }
                for(int i = row2 - 1; i > row1; i--){
                    out.add(matrix[i][col1]);
                }
            }
            row1++; col1++; row2--; col2--;
        }
        return out;
    }
}
发布了557 篇原创文章 · 获赞 500 · 访问量 153万+

猜你喜欢

转载自blog.csdn.net/qq_16234613/article/details/100880470
今日推荐