Backtracking Algorithm in Go
Here's a general implementation of a backtracking algorithm in Go. I'll demonstrate it with the classic N-Queens problem, which is a great example of backtracking.
package main
import "fmt"
// NQueens solves the N-Queens problem using backtracking
func NQueens(n int) [][]string {
// Initialize the board with empty strings
board := make([][]string, n)
for i := range board {
board[i] = make([]string, n)
for j := range board[i] {
board[i][j] = "."
}
}
var result [][]string
var backtrack func(int)
backtrack = func(row int) {
// Base case: if we've placed all queens
if row == n {
// Make a deep copy of the current board
solution := make([][]string, n)
for i := range board {
solution[i] = make([]string, n)
copy(solution[i], board[i])
}
result = append(result, solution...)
return
}
// Try placing a queen in each column of the current row
for col := 0; col < n; col++ {
if isValid(board, row, col, n) {
// Place the queen
board[row][col] = "Q"
// Recurse to the next row
backtrack(row + 1)
// Backtrack: remove the queen
board[row][col] = "."
}
}
}
backtrack(0)
return result
}
// isValid checks if placing a queen at (row, col) is valid
func isValid(board [][]string, row, col, n int) bool {
// Check column
for i := 0; i < row; i++ {
if board[i][col] == "Q" {
return false
}
}
// Check upper left diagonal
for i, j := row-1, col-1; i >= 0 && j >= 0; i, j = i-1, j-1 {
if board[i][j] == "Q" {
return false
}
}
// Check upper right diagonal
for i, j := row-1, col+1; i >= 0 && j < n; i, j = i-1, j+1 {
if board[i][j] == "Q" {
return false
}
}
return true
}
func main() {
n := 4
solutions := NQueens(n)
fmt.Printf("Number of solutions for %d-Queens: %d\n", n, len(solutions))
for i, solution := range solutions {
fmt.Printf("Solution %d:\n", i+1)
for _, row := range solution {
fmt.Println(row)
}
fmt.Println()
}
}
Explanation:
-
Backtracking Function: The backtrack function is defined as a closure that takes the current row as input.
-
Base Case: When we've placed queens in all rows (row == n), we've found a solution and add it to our results.
-
Recursive Case: For each column in the current row, we:
- Check if placing a queen there is valid
- If valid, place the queen and recurse to the next row
- After recursion returns, backtrack by removing the queen
-
Validation: The isValid function checks if placing a queen at a given position would conflict with any previously placed queens.
-
Main Function: Demonstrates how to use the backtracking algorithm to solve the N-Queens problem.
General Backtracking Template:
Here's a more generic template you can adapt for other backtracking problems:
func backtrack(candidate []Type, result *[][]Type, otherParams...) {
// Base case: solution found
if isSolution(candidate) {
// Make a copy of the candidate and add to results
solution := make([]Type, len(candidate))
copy(solution, candidate)
*result = append(*result, solution)
return
}
// Iterate through all possible choices
for _, choice := range getChoices(candidate) {
// Make a choice
candidate = append(candidate, choice)
// Recurse
backtrack(candidate, result, otherParams...)
// Backtrack (undo the choice)
candidate = candidate[:len(candidate)-1]
}
}
You can adapt this template for problems like:
- Generating permutations
- Solving Sudoku
- Finding subsets
- Solving the Knight's Tour problem
- And many other combinatorial problems