Java recursive solution. easy to understand


  • 0
    J
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> result = new ArrayList<>();
            if (matrix.length == 0 || matrix[0].length == 0) return result;
            spiral(matrix, 0, matrix.length, 0, matrix[0].length, result);
            return result;
        }
    
        private void spiral(int[][] matrix, int rs, int re, int cs, int ce, List<Integer> result) {
            if (rs >= re || cs >= ce) return;
            for (int i = cs; i < ce; i++) result.add(matrix[rs][i]);
            for (int i = rs + 1; i < re; i++) result.add(matrix[i][ce - 1]);
            if (re - 1> rs) for (int i = ce - 2; i >= cs; i--) result.add(matrix[re - 1][i]);
            if (re - 2 > rs && cs < ce - 1) for (int i = re - 2; i > rs; i--) result.add(matrix[i][cs]);
            spiral(matrix, rs + 1, re - 1, cs + 1, ce - 1, result);
        }
    

Log in to reply
 

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