A Simple Recursive Solution in Java


  • 0
    H
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        if (n == 0) {
            return result;
        }
        result[0][0] = 1;
        this.generateRound(n, result, 0, 0);
        return result;
    }
    public void generateRound(int n, int[][] matrix, int row, int column) {
        for (int i = row; i < n - 1; i++) {
            matrix[row][i + 1] = matrix[row][i] + 1;
        }
        for (int i = row; i < n - 1; i++) {
            matrix[i + 1][n - 1] = matrix[i][n - 1] + 1; 
        }
        for (int i = n - 1; i > row; i--) {
            matrix[n - 1][i - 1] = matrix[n - 1][i] + 1;
        }
        for (int i = n - 1; i > row + 1; i--) {
            matrix[i - 1][column] = matrix[i][column] + 1;
        }
        if (n > 1 && matrix[row + 1][column + 1] == 0) {
            matrix[row + 1][column + 1] = matrix[row + 1][column] + 1;
            this.generateRound(n - 1, matrix, row + 1, column + 1);
        }
    }

Log in to reply
 

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