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