54. Spiral Matrix

time: O(mn)

space: O(mn)

why

if (rowStart <= rowEnd) { 
// 因為前面有 rowStart++ 和 colEnd--, 值有改動, 所以避免在 while 內邊界超過
// 所以要多加判斷
if (colStart <= colEnd) {
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        
        List<Integer> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0) return res;
        
        int rowStart = 0;
        int rowEnd = matrix.length - 1;
        int colStart = 0;
        int colEnd = matrix[0].length - 1;

        
        while (colStart <= colEnd && rowStart <= rowEnd) {
            
            if (rowStart <= rowEnd) { //都加
                for (int i = colStart; i <= colEnd; i++) {
                    res.add(matrix[rowStart][i]);
                }
            }
            rowStart++;
            
            if (colStart <= colEnd) { //都加
                for (int i = rowStart; i <= rowEnd; i++) { 
                    res.add(matrix[i][colEnd]);
                }
            }
            colEnd--;
            
            if (rowStart <= rowEnd) { //都加
                for (int i = colEnd; i >= colStart; i--) {
                    res.add(matrix[rowEnd][i]);
                }
            }
            rowEnd--;
            
            if (colStart <= colEnd) { //都加
                for (int i = rowEnd; i >= rowStart; i--) {
                    res.add(matrix[i][colStart]);
                }
            }
            colStart++;
            
        }
        return res;
    }
}

Last updated

Was this helpful?