How do I implement DFS and BFS in Go?

Implementing DFS and BFS in Go

Depth-First Search (DFS) and Breadth-First Search (BFS) are fundamental algorithms used for traversing or searching tree or graph data structures. Below, we provide examples of both algorithms implemented in Go.

Keywords: Go, DFS, BFS, Depth-First Search, Breadth-First Search, Graph Algorithms

Description: This content covers the implementation of Depth-First Search and Breadth-First Search algorithms in Go, showcasing usage examples for better understanding.

Depth-First Search (DFS) Implementation

package main import "fmt" type Node struct { Value int Children []*Node } func DFS(node *Node, visited map[int]bool) { if visited[node.Value] { return } visited[node.Value] = true fmt.Println(node.Value) for _, child := range node.Children { DFS(child, visited) } } func main() { root := &Node{Value: 1, Children: []*Node{ {Value: 2, Children: nil}, {Value: 3, Children: []*Node{ {Value: 4, Children: nil}, {Value: 5, Children: nil}}, }, }} visited := make(map[int]bool) DFS(root, visited) }

Breadth-First Search (BFS) Implementation

package main import ( "fmt" "container/list" ) type Node struct { Value int Children []*Node } func BFS(node *Node) { queue := list.New() visited := make(map[int]bool) queue.PushBack(node) for queue.Len() > 0 { element := queue.Front() queue.Remove(element) currentNode := element.Value.(*Node) if visited[currentNode.Value] { continue } visited[currentNode.Value] = true fmt.Println(currentNode.Value) for _, child := range currentNode.Children { queue.PushBack(child) } } } func main() { root := &Node{Value: 1, Children: []*Node{ {Value: 2, Children: nil}, {Value: 3, Children: []*Node{ {Value: 4, Children: nil}, {Value: 5, Children: nil}}, }, }} BFS(root) }

Keywords: Go DFS BFS Depth-First Search Breadth-First Search Graph Algorithms