You need to implement a worker pool pattern. Create numWorkers goroutines that will process BFS queries from a channel:
jobs := make(chan int, len(queries))
results := make(chan BFSResult, len(queries))Define a struct to hold BFS results:
type BFSResult struct {
StartNode int
Order []int
}Launch the specified number of worker goroutines:
for i := 0; i < numWorkers; i++ {
go worker(graph, jobs, results)
}Send all queries to the jobs channel and close it:
for _, query := range queries {
jobs <- query
}
close(jobs)Each worker performs standard BFS using a queue:
func bfs(graph map[int][]int, start int) []int {
visited := make(map[int]bool)
queue := []int{start}
order := []int{}
// ... implement BFS
}The worker function should process jobs until the channel is closed:
func worker(graph map[int][]int, jobs <-chan int, results chan<- BFSResult) {
for start := range jobs {
order := bfs(graph, start)
results <- BFSResult{StartNode: start, Order: order}
}
}Collect all results and convert to the required map format:
resultMap := make(map[int][]int)
for i := 0; i < len(queries); i++ {
result := <-results
resultMap[result.StartNode] = result.Order
}For BFS, use slice operations for queue:
// Dequeue (remove from front)
node := queue[0]
queue = queue[1:]
// Enqueue (add to back)
queue = append(queue, neighbor)