Skip to content

Backtracking (1)

Course: Recursion - chapter 5

Backtracking is a problem-solving algorithmic technique that involves finding a solution incrementally by trying different options and undoing them if they lead to a dead end. It is commonly used in situations where you need to explore multiple possibilities to solve a problem, like searching for a path in a maze or solving puzzles like Sudoku.

Generally, when we are doing recursion, we are kind of doing a backtracking as, from a point if there are 2 possibilities, first we explore one of them, once done we explore the other one.

But backtracking is generally reserved for use cases where you are undoing some changes manually. For example, let’s say in a sudoku solver, you are in some cell currently, let’s call it i,j

Now, let’s say the cell (i, j) can take values v1, v2 and v3. First you choose v1 and update the board using: board[i][j] = v1 . Then you recursively call solve for the next cell:

solve(i+1, j) . Once the recursion for solve(i+1, j) completes, we undo the change we had made i.e board[i][j] = v1 and replace it with the next value v2 i.e.: board[i][j] = v2 and call solve recursively again for the next cell. We continue like this. Once we are done with all possibilities of (i, j) , we backtrack by setting board[i][j] = -1 or some initial value that was present. This appears, as if we never visited cell (i, j) and thus the name backtracking.

Let’s solve the N Queen problem with backtracking.

You have a N * N board, and you need to place N queens such that no queen is attacking each other

We will use backtracking to solve this problem. First let’s identify the states we would need

  1. row: The row we are processing right now. We will go in a row-wise fashion, as we can have at most 1 queen per row. So for the row, we will try determining the column(s) where we can place the queen
  2. board: The current board condition. We already have placed some queens in the previous rows, the board maintains their locations. Instead of the board, we can also maintain a list of columns where we placed the queens.
void solve(int row, int ** board, int n) {
if (row == n) {
// We have successfully placed n queens. Print the board
printBoard(board, n);
return;
}
// Determine where we can place the queen in current row
for(int col = 0; col<n; col++) {
if (!isAttacking(row, col, board, n) {
// isAttacking tells us that if any queen in the current board
// is attacking the cell row, col
board[row][col] = 1; // Place the queen
solve(row+1, board, n); // Recursively solve it for next rows
board[row][col] = 0; // Backtrack / Undo the changes
}
}
}