| 1 | package graph |
| 2 | |
| 3 | // BFS traverses g in breadth-first order starting at v. |
| 4 | // When the algorithm follows an edge (v, w) and finds a previously |
| 5 | // unvisited vertex w, it calls do(v, w, c) with c equal to |
| 6 | // the cost of the edge (v, w). |
| 7 | func BFS(g Iterator, v int, do func(v, w int, c int64)) { |
| 8 | visited := make([]bool, g.Order()) |
| 9 | visited[v] = true |
| 10 | for queue := []int{v}; len(queue) > 0; { |
| 11 | v := queue[0] |
| 12 | queue = queue[1:] |
| 13 | g.Visit(v, func(w int, c int64) (skip bool) { |
| 14 | if visited[w] { |
| 15 | return |
| 16 | } |
| 17 | do(v, w, c) |
| 18 | visited[w] = true |
| 19 | queue = append(queue, w) |
| 20 | return |
| 21 | }) |
| 22 | } |
| 23 | } |