Certainly! Backtracking is a general algorithmic technique for solving problems recursively by trying to build a solution incrementally and abandoning (backtracking from) a partial candidate as soon as it determines that the candidate cannot possibly lead to a valid solution.
Below is an example of a backtracking algorithm in Go. We'll use the classic "N-Queens Problem" as an example, where the goal is to place N queens on an NxN chessboard so that no two queens threaten each other.
Backtracking Algorithm in Go: N-Queens Problem
go
package main
import (
"fmt"
)
// SolveNQueens solves the N-Queens problem using backtracking.
func SolveNQueens(n int) [][]string {
var solutions [][]string
board := make([][]bool, n)
for i := range board {
board[i] = make([]bool, n)
}
// Helper function to check if a queen can be placed at board[row][col]
isSafe := func(row, col int) bool {
// Check this row on the left side
for i := 0; i < col; i++ {
if board[row][i] {
return false
}
}
// Check upper diagonal on the left side
for i, j := row, col; i >= 0 && j >= 0; i, j = i-1, j-1 {
if board[i][j] {
return false
}
}
// Check lower diagonal on the left side
for i, j := row, col; i < n && j >= 0; i, j = i+1, j-1 {
if board[i][j] {
return false
}
}
return true
}
// Backtracking function to solve the problem
var backtrack func(col int)
backtrack = func(col int) {
// If all queens are placed, add the current board configuration to solutions
if col == n {
solution := make([]string, n)
for i := 0; i < n; i++ {
rowStr := ""
for j := 0; j < n; j++ {
if board[i][j] {
rowStr += "Q"
} else {
rowStr += "."
}
}
solution[i] = rowStr
}
solutions = append(solutions, solution)
return
}
// Try placing a queen in each row of the current column
for row := 0; row < n; row++ {
if isSafe(row, col) {
// Place the queen
board[row][col] = true
// Recur to place the rest of the queens
backtrack(col + 1)
// Backtrack: remove the queen
board[row][col] = false
}
}
}
// Start backtracking from the first column
backtrack(0)
return solutions
}
func main() {
n := 4 // Change this value to test with different board sizes
solutions := SolveNQueens(n)
fmt.Printf("Found %d solutions for %dx%d board:\n", len(solutions), n, n)
for _, solution := range solutions {
for _, row := range solution {
fmt.Println(row)
}
fmt.Println()
}
}
Explanation of the Code
Board Representation:
The board is represented as a 2D slice of booleans ([][]bool), where true indicates the presence of a queen and false indicates an empty cell.
Safety Check:
The isSafe function checks whether it's safe to place a queen at a given position (row, col) by ensuring no other queen is in the same row, upper-left diagonal, or lower-left diagonal.
Backtracking:
The backtrack function tries to place queens column by column. For each column, it iterates through all rows and attempts to place a queen if it's safe.
If a valid placement is found, it moves to the next column recursively.
If no valid placement is possible, it backtracks by removing the previously placed queen and tries other possibilities.
Solution Collection:
When all queens are successfully placed (i.e., when col == n), the current board configuration is converted into a string representation and added to the solutions list.
Output:
The main function prints all valid configurations of the board.
Example Output for n = 4
For a 4x4 board, the program will output:
code
Found 2 solutions for 4x4 board:
.Q..
...Q
Q...
..Q.
..Q.
Q...
...Q
.Q..
Each line represents a row on the chessboard, where Q denotes a queen and . denotes an empty cell.
Complexity
Time Complexity: The worst-case time complexity is O(N!), as there are N! permutations of queen placements in the worst case.
Space Complexity: The space complexity is O(N2) due to the board representation.
This implementation is efficient for small values of N but may become computationally expensive for larger boards. You can optimize further by using techniques like bitmasking, but this implementation demonstrates the core backtracking approach clearly.
Let me know if you'd like to explore other backtracking problems or optimizations!