How to Implement BFS and DFS in Go

Implement BFS using a queue and DFS using a stack or recursion to traverse graphs or trees in Go. Use a `queue` slice for BFS and a recursive function or `stack` slice for DFS.

How to Implement BFS and DFS in Go

Implement BFS using a queue and DFS using a stack or recursion to traverse graphs or trees in Go. Use a queue slice for BFS and a recursive function or stack slice for DFS.

package main

type Node struct {
	Neighbors []*Node
}

func BFS(start *Node) {
	if start == nil {
		return
	}
	visited := make(map[*Node]bool)
	queue := []*Node{start}
	for len(queue) > 0 {
		node := queue[0]
		queue = queue[1:]
		if visited[node] {
			continue
		}
		visited[node] = true
		// Process node
		for _, neighbor := range node.Neighbors {
			if !visited[neighbor] {
				queue = append(queue, neighbor)
			}
		}
	}
}

func DFS(node *Node, visited map[*Node]bool) {
	if node == nil || visited[node] {
		return
	}
	visited[node] = true
	// Process node
	for _, neighbor := range node.Neighbors {
		DFS(neighbor, visited)
	}
}