Skip to content

Commit

Permalink
Merge pull request #545 from riyarane46/main
Browse files Browse the repository at this point in the history
added rat in a maze and kth permutation problem in backtracking folder
  • Loading branch information
UTSAVS26 authored Nov 4, 2024
2 parents dc1a20b + 20342ee commit d5b29d1
Show file tree
Hide file tree
Showing 3 changed files with 149 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,26 @@ The **N-Queens Problem** is a classic puzzle where the goal is to place \(N\) qu

- **Use Case**: Resource allocation and optimization problems, where multiple entities must be placed in non-conflicting positions (e.g., server load balancing).

### 6. **Rat in a Maze**

The **Rat in a Maze** problem involves finding a path for a rat from the source to the destination in a maze represented by a binary matrix.

- **Backtracking Approach**: Start from the source and explore possible moves (usually up, down, left, right). If a move leads to a valid path, continue; otherwise, backtrack and try another direction.

- **Time Complexity**: \(O(4^{n^2})\) in the worst case, where \(n\) is the size of the maze.

- **Use Case**: Pathfinding algorithms, robot navigation in constrained environments.

### 7. **Kth Permutation**

The **Kth Permutation** problem involves finding the kth permutation of a set of n numbers in lexicographic order.

- **Backtracking Approach**: Generate permutations in lexicographic order until the kth permutation is reached. Alternatively, use a more efficient factorial number system approach.

- **Time Complexity**: \(O(n!)\) for naive approach, \(O(n^2)\) for optimized factorial number system approach.

- **Use Case**: Combinatorial problems, generating specific arrangements in lexicographic order.

---

## Key Differences Between Backtracking Applications:
Expand All @@ -83,12 +103,14 @@ The **N-Queens Problem** is a classic puzzle where the goal is to place \(N\) qu
| **Knight's Tour** | \(O(8^n)\) | Chess puzzle solvers, Pathfinding |
| **Maze Solving** | \(O(4^n)\) | Robotics, Navigation Systems |
| **N-Queens** | \(O(N!)\) | Resource allocation, Server optimization |
| **Rat in a Maze** | \(O(4^{n^2})\) | Pathfinding, Robot navigation |
| **Kth Permutation** | \(O(n^2)\) | Combinatorial problems, Lexicographic ordering |

---

## Conclusion

**Backtracking** is a versatile and powerful technique for solving constraint-based problems. By exploring all possibilities and eliminating invalid paths through backtracking, this approach enables the efficient solving of complex combinatorial problems. Applications like **Graph Coloring**, **Hamiltonian Cycle**, **Knight's Tour**, **Maze Solving**, and the **N-Queens Problem** showcase the wide applicability of backtracking, from puzzle-solving to real-world optimization tasks.
**Backtracking** is a versatile and powerful technique for solving constraint-based problems. By exploring all possibilities and eliminating invalid paths through backtracking, this approach enables the efficient solving of complex combinatorial problems. Applications like **Graph Coloring**, **Hamiltonian Cycle**, **Knight's Tour**, **Maze Solving**,**N-Queens Problem** ,**Rat in a Maze** and **Kth Permutation** showcase the wide applicability of backtracking, from puzzle-solving to real-world optimization tasks.

Mastering backtracking is essential for understanding and solving a range of computational problems, making it a critical tool in algorithmic design.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class Solution:
def getPermutation(self, n: int, k: int) -> str:
# Initialize the list of numbers from 1 to n
numbers = list(range(1, n + 1))
# Initialize the result string
result = []
# Decrement k by 1 to convert to 0-based index
k -= 1

def backtrack(nums, k, path):
if not nums:
# If no numbers left, we've found the kth permutation
return True

# Calculate the factorial of the remaining numbers
factorial = 1
for i in range(1, len(nums)):
factorial *= i

for i in range(len(nums)):
if k >= factorial:
# Skip this number, as it's not part of the kth permutation
k -= factorial
else:
# Add the current number to the path
path.append(str(nums[i]))
# Remove the used number from the list
nums.pop(i)
# Recursively build the rest of the permutation
if backtrack(nums, k, path):
return True
# If not successful, backtrack
nums.insert(i, int(path.pop()))

# Move to the next number
k %= factorial

return False

# Start the backtracking process
backtrack(numbers, k, result)

# Join the result list into a string and return
return ''.join(result)

# Example usage
if __name__ == "__main__":
solution = Solution()
n = 4
k = 9
print(f"The {k}th permutation of {n} numbers is: {solution.getPermutation(n, k)}")
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
def print_solution(solution):
"""
Print the solution matrix.
"""
for row in solution:
print(row)

def is_safe(maze, x, y):
"""
Check if the given position (x, y) is safe to move to.
Returns True if the position is within the maze and is not blocked.
"""
n = len(maze)
return 0 <= x < n and 0 <= y < n and maze[x][y] == 1

def solve_maze(maze):
"""
Main function to solve the maze using backtracking.
Returns the solution matrix if a path is found, otherwise returns None.
"""
n = len(maze)
# Create a solution matrix initialized with zeros
solution = [[0 for _ in range(n)] for _ in range(n)]

if solve_maze_util(maze, 0, 0, solution):
return solution
else:
print("No solution exists.")
return None

def solve_maze_util(maze, x, y, solution):
"""
Recursive utility function to solve the maze.
"""
n = len(maze)

# Base case: if we've reached the destination
if x == n - 1 and y == n - 1 and maze[x][y] == 1:
solution[x][y] = 1
return True

# Check if the current position is safe to move
if is_safe(maze, x, y):
# Mark the current cell as part of the solution path
solution[x][y] = 1

# Move forward in x direction
if solve_maze_util(maze, x + 1, y, solution):
return True

# If moving in x direction doesn't work, move down in y direction
if solve_maze_util(maze, x, y + 1, solution):
return True

# If none of the above movements work, backtrack
solution[x][y] = 0
return False

return False

# Example usage
if __name__ == "__main__":
# 1 represents open path, 0 represents blocked path
maze = [
[1, 0, 0, 0],
[1, 1, 0, 1],
[0, 1, 0, 0],
[1, 1, 1, 1]
]

solution = solve_maze(maze)

if solution:
print("Solution found:")
print_solution(solution)

0 comments on commit d5b29d1

Please sign in to comment.