Backtracking Programming
Backtracking Programming
Concept of Backtracking
In simpler terms, backtracking is a way of systematically searching for a solution by trying out
different possibilities and backtracking (going back) when a solution is not possible. It is often
referred to as a depth-first search technique in solving problems.
• Combinatorics
• Permutations
• Combinations
• Puzzles and games (e.g., Sudoku, N-Queens problem)
Advantages of Backtracking
Disadvantages of Backtracking
Applications of Backtracking
Backtracking is a powerful technique used to solve many types of problems. Some common
applications include:
Problem Statement:
The safe check ensures that the new queen does not share the same column or diagonal with any
previously placed queens.
• Time Complexity: The worst-case time complexity of backtracking for the N-Queens
problem is O(N!) because for each row, we attempt placing queens in all columns, and in
the worst case, we might try every possible arrangement of queens.
• Space Complexity: The space complexity is O(N) for the recursion stack and the space
used by the board.
Problem:
We need to place 4 queens on a 4x4 chessboard such that no two queens can attack each other.
The solution involves placing queens such that they do not share the same row, column, or
diagonal.
. . . .
. . . .
. . . .
. . . .
Q . . .
. . Q .
. . . .
. . . .
Q . . .
. . Q .
. . . Q
. . . .
Q . . .
. . Q .
. . . Q
. Q . .
Q . . .
. . Q .
. . . Q
. Q . .
7. Backtrack: Now that we've found a solution, backtrack to explore other possible
arrangements.
8. Exploring Other Columns: We explore different columns for the queens in each row,
repeating the process until all possible solutions are found.
Second Solution:
After backtracking and exploring other possibilities, we find another valid arrangement:
. Q . .
Q . . .
. . . Q
. . Q .
Conclusion:
For N = 4, there are 2 distinct solutions to the N-Queens problem. These solutions are:
1. Solution 1:
Q . . .
. . Q .
. . . Q
. Q . .
2. Solution 2:
. Q . .
Q . . .
. . . Q
. . Q .
Both solutions ensure that no two queens threaten each other in terms of rows, columns, or
diagonals.