Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. It works in incremental way and is an optimization over the Naive solution where all possible configurations are generated and tried.

## Concepts

Backtracking works in an incremental way to attack problems.

Typically, we start from an empty solution vector and one by one add items. When we add an item, we check if adding the current item violates the problem constraint, if it does then we remove the item and try other alternatives. If none of the alternatives work out then we go to previous stage and remove the item added in the previous stage.

If we reach the initial stage back then we say that no solution exists. If adding an item doesn’t violate constraints then we recursively add items one by one. If the solution vector becomes complete then we print the solution.

### Psudo Code

Following is the Backtracking algorithm for Knight’s tour problem.

```
IF all squares are visited
print the solution
ELSE
a) Add one of the next moves to solution vector and recursively
check if this move leads to a solution. (A Knight can make maximum
eight moves. We choose one of the 8 moves in this step).
b) If the move chosen in the above step doesn't lead to a solution
then remove this move from the solution vector and try other
alternative moves.
c) If none of the alternatives work then return false (Returning false
will remove the previously added item in recursion and if false is
returned by the initial call of recursion then "no solution exists" )
```

## Sample Problems (from LeetCode)

### N-Queens (51)

Problem:

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.

Example:

```
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
```

Solution:

1 | # ugly but easy to understand |

### Word Search(79)

Problem:

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

```
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
```

Solution:

1 | import numpy as np |

## Conclusion

### Steps

Using the solution of N-Queen as a template to solve all backtracking problems.

First we should figure out what does the backtracking function do. In N-Queen, it is a function casted over each column:

- columns: 1st loop. examine one column per backtracking function call.

Then, in the backtracking function:

- row: 2nd loop. check every row of a certain col to find all possible next move.
- neighborhood: 3rd loop: check if the neighbors of (row,col) is valid for further move.

### Return Types

- return all possible solutions – N-Queen
- return if exist any solution – Word Search
## Reference

1. N-Queen Problem - GeeksforGeeks