Easy 2ms Java Recursive Solution, for both Spiral Matrix I and II


  • 0

    Sprial Matrix 1

    public List<Integer> spiralOrder(int[][] matrix) {
        if(matrix.length==0) return new ArrayList<Integer>();
        return spiralOrderRecursive(matrix, 0);
    }
    public List<Integer> spiralOrderRecursive(int[][] matrix, int level) {       
        List<Integer> result = new ArrayList<Integer>();
        for(int head = level;head<matrix[0].length-level; head++) result.add(matrix[level][head]);
        if(matrix.length-2*level==1) return result;
        for(int righ = level+1;righ<matrix.length-level; righ++) result.add(matrix[righ][matrix[0].length-level-1]);
        if(matrix[0].length-2*level==1) return result;
        for(int tail = matrix[0].length-level-2;tail>=level; tail--) result.add(matrix[matrix.length-level-1][tail]);
        if(matrix.length-2*level==2) return result;
        for(int left = matrix.length-level-2;left>level; left--) result.add(matrix[left][level]);
        if(matrix[0].length-2*level==2) return result;
        result.addAll(spiralOrderRecursive(matrix, level+1));
        return result;
    }
    

    Sprial Matrix 2

    public int[][] generateMatrix(int n) {
        if(n==0) return new int[n][n];
        return generateMatrixRecursive(new int[n][n], 0, 1);
    }
    public int[][] generateMatrixRecursive(int[][] matrix, int level, int num) {   
        for(int head = level;head<matrix[0].length-level; head++) matrix[level][head]=num++;
        if(matrix.length-2*level==1) return matrix;
        for(int righ = level+1;righ<matrix.length-level; righ++) matrix[righ][matrix[0].length-level-1]=num++;
        if(matrix[0].length-2*level==1) return matrix;
        for(int tail = matrix[0].length-level-2;tail>=level; tail--) matrix[matrix.length-level-1][tail]=num++;
        if(matrix.length-2*level==2) return matrix;
        for(int left = matrix.length-level-2;left>level; left--) matrix[left][level]=num++;
        if(matrix[0].length-2*level==2) return matrix;
        return generateMatrixRecursive(matrix, level+1, num);
    }

Log in to reply
 

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