LeetCode:54.スパイラルマトリックス時計回りの印刷行列

试题
スパイラルために行列のすべての要素を返し、m×n個の要素(m行、n列)の行列を考えます。

例1:

INPUT:
[
[1、2 ,. 3]、
[4 ,. 5 ,. 6]、
[7 ,. 8 ,. 9]。
]
出力:[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