Java - solve layer by layer and use recursion


  • 0
    H
    public int[][] generateMatrix(int n) {
    
            if (n <= 0)
                return new int[0][0];
    
            int[][] mat = new int[n][n];
    
            fillMatrix(mat, 0, n, 1);   // fill from 0 to n, full matrix
    
            return mat;
        }
    
        private void fillMatrix(int[][] mat, int a, int  b, int index) {
            if (a == b)     // even n will end here
                return;
    
            if (a == b - 1) {   // odd n will end here, need to add the last index
                mat[a][a] = index;
                return;
    
            }
    
            for (int j = a; j < b - 1; j++) {   // fill left->right, n-1 elements
                mat[a][j] = index++;
            }
    
            for (int i = a; i < b - 1; i++) {   // fill up->down
                mat[i][b-1] = index++;
            }
    
            for (int j = b-1; j > a; j--) { // fill right->left
                mat[b-1][j] = index++;
            }
    
            for (int i = b-1; i > a; i--) { // fill down->up
                mat[i][a] = index++;
            }
    
            fillMatrix(mat, a+1, b-1, index);   // go to inner layer
    
        }

Log in to reply
 

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