Java Simple Solution (3 ms) One Loop


  • 0
    K

    class Solution {

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        
        if (matrix.length == 0) {
            return list;
        }
    
        int x = 0, y = 0, dx = 1, dy = 0, left = 0, top = 0, right = matrix[0].length, bottom = matrix.length, temp;
    
        while (left < right && top < bottom) { 
            list.add(matrix[y][x]);
    
            if (x + dx < left || x + dx >= right || y + dy < top || y + dy >= bottom) {
                // Direction   dx  dy
                //     right   1    0
                //     down    0    1
                //     left   -1    0
                //     up      0   -1
                
                // change direction
                temp = dx;
                dx = -dy;
                dy = temp;
    
                // update boundary
                left += Math.max(dx, 0);    // only update when going right direction (dx == 1)
                right += Math.min(dx, 0);   // only update when going left direction (dx == -1)
                top  += Math.max(dy, 0);    // only update when going down direction (dy == 1)
                bottom += Math.min(dy, 0);  // only update when going up direction (dy == -1)
            }
            
            // jump to next slot
            x += dx;
            y += dy;
        }
        return list;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.