Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions backtracking/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Backtracking Algorithms

This folder contains implementations of classic backtracking problems with detailed explanations and solutions.

## Problems Included

### 1. N-Queens Problem (`n_queens.cpp`)
- **Problem**: Place N queens on an N×N chessboard such that no two queens attack each other
- **Time Complexity**: O(N!)
- **Space Complexity**: O(N²)
- **Key Features**:
- Finds one solution
- Finds all possible solutions
- Detailed safety checking for queen placement

### 2. Rat in Maze (`rat_in_maze.cpp`)
- **Problem**: Find a path from top-left to bottom-right corner in a maze
- **Time Complexity**: O(2^(n²)) in worst case
- **Space Complexity**: O(n²)
- **Key Features**:
- Finds one solution path
- Finds all possible paths
- Handles blocked and open cells

### 3. Sudoku Solver (`sudoku_solver.cpp`)
- **Problem**: Solve a 9×9 Sudoku puzzle using backtracking
- **Time Complexity**: O(9^(n×n))
- **Space Complexity**: O(n×n)
- **Key Features**:
- Validates Sudoku rules (row, column, 3×3 box)
- Finds complete solution
- Handles empty cells (represented by 0)

## How to Run

### Compilation
```bash
g++ -o n_queens n_queens.cpp
g++ -o rat_maze rat_in_maze.cpp
g++ -o sudoku_solver sudoku_solver.cpp
```

### Execution
```bash
./n_queens
./rat_maze
./sudoku_solver
```

## Backtracking Algorithm Pattern

All these problems follow the classic backtracking pattern:

1. **Choose**: Make a choice (place queen, move in maze, fill cell)
2. **Explore**: Recursively solve the subproblem
3. **Unchoose**: Backtrack if the choice doesn't lead to a solution

```cpp
bool solve(parameters) {
if (base_case) {
return true; // Solution found
}

for (each possible choice) {
if (isValid(choice)) {
makeChoice(choice);
if (solve(updated_parameters)) {
return true; // Solution found
}
undoChoice(choice); // Backtrack
}
}

return false; // No solution found
}
```

## Key Concepts

- **Constraint Satisfaction**: Each problem has specific constraints that must be satisfied
- **State Space Tree**: The recursive calls form a tree of possible states
- **Pruning**: Invalid branches are pruned early to improve efficiency
- **Backtracking**: When a path doesn't lead to a solution, we undo the last choice

## Learning Outcomes

After studying these implementations, you'll understand:
- How to identify backtracking problems
- How to design recursive solutions with backtracking
- How to implement constraint checking
- How to optimize backtracking algorithms
- Common patterns in backtracking problems

## Extensions

You can extend these problems by:
- Adding more constraints
- Finding all solutions instead of just one
- Optimizing the algorithms further
- Implementing different variations of the problems
145 changes: 145 additions & 0 deletions backtracking/n_queens.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
Time Complexity: O(N!)
Space Complexity: O(N^2)

Explanation:
The N-Queens problem is a classic backtracking problem where we need to place N queens
on an N×N chessboard such that no two queens attack each other.

Algorithm:
1. Start with the first row and try to place a queen in each column
2. For each placement, check if it's safe (no conflicts with previously placed queens)
3. If safe, place the queen and recursively solve for the next row
4. If we reach the last row successfully, we found a solution
5. If not, backtrack by removing the queen and try the next column
6. Continue until all solutions are found

The isSafe function checks:
- Column conflicts: No other queen in the same column
- Diagonal conflicts: No other queen in the upper left and upper right diagonals

This approach uses backtracking to systematically explore all possible placements
and find valid solutions.
*/
#include <iostream>
#include <vector>
using namespace std;

class NQueens {
private:
int n;
vector<vector<int>> board;

bool isSafe(int row, int col) {
// Check column
for (int i = 0; i < row; i++) {
if (board[i][col] == 1) {
return false;
}
}

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

// Check upper right diagonal
for (int i = row, j = col; i >= 0 && j < n; i--, j++) {
if (board[i][j] == 1) {
return false;
}
}

return true;
}

void printBoard() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << (board[i][j] == 1 ? "Q " : ". ");
}
cout << endl;
}
cout << endl;
}

public:
NQueens(int size) : n(size) {
board.resize(n, vector<int>(n, 0));
}

bool solveNQueens(int row = 0) {
// Base case: all queens are placed
if (row == n) {
printBoard();
return true;
}

// Try placing queen in each column of current row
for (int col = 0; col < n; col++) {
if (isSafe(row, col)) {
// Place queen
board[row][col] = 1;

// Recursively place queens in remaining rows
if (solveNQueens(row + 1)) {
return true; // Found a solution
}

// Backtrack: remove queen
board[row][col] = 0;
}
}

return false; // No solution found
}

void findAllSolutions(int row = 0) {
// Base case: all queens are placed
if (row == n) {
printBoard();
return;
}

// Try placing queen in each column of current row
for (int col = 0; col < n; col++) {
if (isSafe(row, col)) {
// Place queen
board[row][col] = 1;

// Recursively place queens in remaining rows
findAllSolutions(row + 1);

// Backtrack: remove queen
board[row][col] = 0;
}
}
}
};

int main() {
int n;
cout << "Enter the number of queens (board size): ";
cin >> n;

if (n <= 0) {
cout << "Invalid input! Please enter a positive integer." << endl;
return 1;
}

NQueens solver(n);

cout << "\nOne solution for " << n << " queens problem:" << endl;
if (!solver.solveNQueens()) {
cout << "No solution exists for " << n << " queens!" << endl;
}

cout << "\nAll solutions for " << n << " queens problem:" << endl;
solver.findAllSolutions();

return 0;
}


Loading