Java clean solution


  • 1
    A
     public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> result = new ArrayList<>();
            if(matrix.length == 0) {
                return result;
            }
            int left = 0, top = 0, bottom = matrix.length - 1, right = matrix[0].length - 1;
    
            while(left <= right && top <= bottom) {
                //Go right
                for(int i = left; i <= right; i++) {
                    result.add(matrix[top][i]);
                }
                top++;
                //Check for when going left
                if(top > bottom) {
                    continue;
                }
                //Go down
                for(int i = top; i <= bottom; i++) {
                    result.add(matrix[i][right]);
                }
                right--;
                //Check for when going up
                if(right < left) {
                    continue;
                }
                //Go left
                for(int i = right; i >= left; i--) {
                    result.add(matrix[bottom][i]);
                }
                bottom--;
                //Go up
                for(int i = bottom; i >= top; i--) {
                    result.add(matrix[i][left]);
                }
                left++;
            }
            return result;
        }
    

Log in to reply
 

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