func(v *Vertex) Dfs(f func(*Vertex), seen map[*Vertex]bool) {
seen[v] = true
f(v)
for next, isEdge := range v.Neighbours {
if isEdge && !seen[next] {
next.Dfs(f, seen)
}
}
}
Dfs is a method of type *Vertex : the receiver is the start node. The function f is a parameter of the traversal method. Start with an empty map as initial seen parameter.
func(v *Vertex[L]) Dfs(f func(*Vertex[L]), seen map[*Vertex[L]]bool) {
seen[v] = true
f(v)
for next, isEdge := range v.Neighbours {
if isEdge && !seen[next] {
next.Dfs(f, seen)
}
}
}
Dfs is a method of type *Vertex : the receiver is the start node. The function f is a parameter of the traversal method. Start with an empty map as initial seen parameter. Vertex has a type parameter L as its node label.
defdepth_first(start, f):
seen = set()
stack = [start]
while stack:
vertex = stack.pop()
f(vertex)
seen.add(vertex)
stack.extend(
v for v in vertex.adjacent if v notin seen
)
It's best to not recurse in Python when the structure size is unknown, since we have a fixed, small stack size.
def depth_first(start, f):
seen = set()
stack = [start]
while stack:
vertex = stack.pop()
f(vertex)
seen.add(vertex)
stack.extend(
v for v in vertex.adjacent if v not in seen
)