Java solution using recursion


  • 0
    H

    I appreciate if anyone can improve the base case.

       public List<Integer> spiralOrder(int[][] matrix) { 
            List<Integer> result = new ArrayList<Integer>(); 
            if (null == matrix || 0 == matrix.length) { 
                return result; 
            } 
            spiralOrderHelper(matrix, result, 0, 0, matrix.length - 1, matrix[0].length - 1); 
            return result; 
        } 
     
        private void spiralOrderHelper(int[][] matrix, List<Integer> result, int row, int col, int rowDown, int colRight) { 
            // even base case
            if (row > rowDown || col > colRight) {
                return;
            }
            // odd base case
            if (row == rowDown) {
                for (int i = col; i <= colRight; i++) {
                    result.add(matrix[row][i]);
                }
                return;
            }
            if (col == colRight) {
                for (int i = row; i <= rowDown; i++) {
                    result.add(matrix[i][col]);
                }
                return;
            }
            // start from the up-left corner 
            for (int i = col; i <= colRight - 1; i++) { 
                result.add(matrix[row][i]); 
            } 
            for (int i = row; i <= rowDown - 1; i++) { 
                result.add(matrix[i][colRight]); 
            } 
            for (int i = colRight; i > col; i--) { 
                result.add(matrix[rowDown][i]); 
            } 
            for (int i = rowDown; i > row; i--) { 
                result.add(matrix[i][col]); 
            } 
            spiralOrderHelper(matrix, result, row + 1, col + 1, rowDown - 1, colRight - 1); 
        }

Log in to reply
 

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