LeetCode 54 螺旋矩阵

// LeetCode 54 螺旋矩阵
// 分情况讨论,注意终止条件,奇偶统一,用上取整

class Solution {
    public List spiralOrder(int[][] matrix) {
        if (matrix.length == 0) return new ArrayList<>();
        List list = new ArrayList<>();
        int n = matrix.length;
        int m = matrix[0].length;
        int k = 0;
        int min = Math.min((n + 1) / 2 , (m + 1) / 2);
        while(k < min) {

            for (int j = k; j < m - k; j ++){
                list.add(matrix[k][j]);
            }

            for (int i = k + 1; i < n - k; i ++){
                list.add(matrix[i][m - k - 1]);
            }

            if (k == n - k - 1 || k == m - k - 1) break; 
            // 如果矩阵某一维是奇数,不判的话会重复
            for (int j = m - k - 2; j > k; j --) {
                list.add(matrix[n - k - 1][j]);
            }
            
            for (int i = n - k - 1; i > k; i --){
                list.add(matrix[i][k]);
            }
            
            k ++;
        }
        return list;
    }
}

 

你可能感兴趣的:(LeetCode,Java,数组,LeetCode,54,螺旋矩阵,Java)