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;
}
}
}