Short recursive java code, easy to understand


  • 0
    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            if (matrix.length == 0) return new ArrayList<Integer>();
            
            int numRows = matrix.length;
            int numCols = matrix[0].length;
            
            List<Integer> result = new ArrayList<>();
            
            search(result, matrix, 0, 0, numRows - 1, numCols - 1);
            
            return result;
        }
        
        private void search(List<Integer> result, int[][] matrix, int startRow, int startCol, int endRow, int endCol) {
            if (startRow > endRow || startCol > endCol) return;
            
            if (startRow == endRow) {
                for (int i = startCol; i <= endCol; i++) result.add(matrix[startRow][i]);
                return;
            } else if (startCol == endCol) {
                for (int i = startRow; i <= endRow; i++) result.add(matrix[i][startCol]);
                return;
            } else {
                for (int i = startCol; i <= endCol; i++) result.add(matrix[startRow][i]);
                for (int i = startRow + 1; i <= endRow; i++) result.add(matrix[i][endCol]);
                for (int i = endCol - 1; i >= startCol; i--) result.add(matrix[endRow][i]);
                for (int i = endRow - 1; i >= startRow + 1; i--) result.add(matrix[i][startCol]);
                
                search(result, matrix, ++startRow, ++startCol, --endRow, --endCol);
            }
        }
    }
    

Log in to reply
 

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