LeetCode: 54. Spiral Matrix clockwise print 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]
]
the Output: [1,2,3,6,9,8,7,4,5]
Code
cis hour to print

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;
    }
}
Published 557 original articles · won praise 500 · Views 1.53 million +

Guess you like

Origin blog.csdn.net/qq_16234613/article/details/100880470