简体   繁体   中英

Why this program find only one solution?

I want to code a program which finds all solutions for latin square. I want to do it using backtracking. I solved the n-queens problem using a similar method and it works. This code finds only the first solution and it doesn't back track.

public static boolean isSafe(int[][] board, int row, int col) {

    for(int i = 0; i < board.length; i++) {
        if(row != i) {
            if(board[i][col] == board[row][col]) return false;
        }
        if(col != i) {
            if(board[row][i] == board[row][col]) return false;
        }
    }
    return true;
}

public static void enumerate(int N) {
    int[][] board = new int[N][N];
    enumerate(board, 0, 0);
}

public static void enumerate(int[][] board, int row, int col) {
    int boardSize = board.length;
    if (col == boardSize ) {
        System.out.println();
        print(board);
        SaveToFile.saveSquare("Latin", "BT", board, boardSize);

    }
    else {
        for (int i = 1; i <= boardSize; i++) {
            board[row][col] = i; 
            if (isSafe(board, row, col)) {
                if(row+1 == boardSize) {
                    enumerate(board, 0, col+1);
                }
                else {
                    enumerate(board, row+1, col);
                }
            }
        }
    }
}

public static void print(int[][] board) {
    for(int i=0; i<board.length;i++) {
        for(int j=0; j<board.length; j++) {
            System.out.print(" "+board[i][j]+" ");
        }
        System.out.println();
    }
    System.out.println();
}

public static void main(String[] args) {

    for(int i = 2; i <=2; i++) {
        SaveToFile.createFile("Latin", "BT", i);
        enumerate(i);
    }
}

I know that my code looks bad but I'll refactor it later ;) thanks for help :)

You have to clear the value you are setting in the board after the recursive calls:

public static void enumerate(int[][] board, int row, int col) {
    int boardSize = board.length;
    if (col == boardSize ) {
        System.out.println();
        print(board);
        SaveToFile.saveSquare("Latin", "BT", board, boardSize);

    }
    else {
        for (int i = 1; i <= boardSize; i++) {
            board[row][col] = i;
            if (isSafe(board, row, col)) {
                if(row+1 == boardSize) {
                    enumerate(board, 0, col+1);
                }
                else {
                    enumerate(board, row+1, col);
                }
            }
            //RESET!!!
            board[row][col] = 0;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM