How to implement a backtracking algorithm in Java

A backtracking algorithm can be implemented in Java using a recursive function. The basic structure of the algorithm includes a base case to stop the recursion, and a recursive case to explore different options.

Here is an example of a simple backtracking algorithm in Java that finds all the possible solutions for the “n-queens” problem:

In this example, the solveNQUtil function is a recursive function that tries to place queens in different rows of a given column. If it finds a safe place to put a queen, it marks that cell with 1 and recursively tries to place the next queen. If it reaches a point where it can’t place any more queens, it backtracks by changing the last placed queen’s cell value back to 0 and tries a different row in the same column.

public class NQueens {
    static int N = 4;

    /* A utility function to print solution */
    static void printSolution(int board[][]) {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                System.out.print(" " + board[i][j] + " ");
            System.out.println();
        }
    }

    /* A utility function to check if a queen can
       be placed on board[row][col]. Note that this
       function is called when "col" queens are
       already placed in columns from 0 to col -1.
       So we need to check only left side for
       attacking queens */
    static boolean isSafe(int board[][], int row, int col) {
        int i, j;

        /* Check this row on left side */
        for (i = 0; i < col; i++)
            if (board[row][i] == 1)
                return false;

        /* Check upper diagonal on left side */
        for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
            if (board[i][j] == 1)
                return false;

        /* Check lower diagonal on left side */
        for (i = row, j = col; j >= 0 && i < N; i++, j--)
            if (board[i][j] == 1)
                return false;

        return true;
    }

    /* A recursive utility function to solve N
       Queen problem */
    static boolean solveNQUtil(int board[][], int col) {
        /* base case: If all queens are placed
           then return true */
        if (col >= N)
            return true;

        /* Consider this column and try placing
           this queen in all rows one by one */
        for (int i = 0; i < N; i++) {
            /* Check if the queen can be placed on
               board[i][col] */
            if (isSafe(board, i, col)) {
                /* Place this queen in board[i][col] */
                board[i][col] = 1;

                /* recur to place rest of the queens */
                if (solveNQUtil(board, col + 1) == true)
                    return true;

                /* If placing queen in board[i][col
                   doesn't lead to a solution then
                   remove queen from board[i][col] */
                board[i][col] = 0; // BACKTRACK
            }
        }

        /* If the queen can not be placed in any row in
           this column col then return false */
        return false;
    }

    /* This function solves the N Queen problem using
       Backtracking. It mainly uses solveNQUtil() to
       solve the problem. It returns false if queens
       cannot be placed, otherwise it returns true and
       prints the placement of queens in the form of a
       2Dimensional array.
       static void solveNQ() {
       int board[][] = new int[N][N];
    if (solveNQUtil(board, 0) == false) {
        System.out.print("Solution does not exist");
        return;
    }

    printSolution(board);
}

// Driver code
public static void main(String[] args) {
    solveNQ();
}
}

Note that this is a simple example, and backtracking can be implemented in various ways depending on the problem you are trying to solve.

Leave a Reply