Skip to content

Instantly share code, notes, and snippets.

@sausheong
Created May 3, 2022 03:21
Show Gist options
  • Save sausheong/f22aff44b8595fa9553d9bf7f145ed94 to your computer and use it in GitHub Desktop.
Save sausheong/f22aff44b8595fa9553d9bf7f145ed94 to your computer and use it in GitHub Desktop.
mst
func (g *Graph) isCyclic(name string) (yes bool) {
stack := &Stack{}
visited := make(map[string]bool)
startNode := g.GetNode(name)
// use a 2 node array with first node as the from node and the second as the to node
stack.Push([2]*Node{startNode, startNode})
for len(stack.nodes) > 0 {
n := stack.Pop()
// if it's not visited before
if !visited[n[1].name] {
visited[n[1].name] = true // set to visited
// get edges
edges := g.Edges[n[1].name]
for _, edge := range edges {
// if this is not the from node
if edge.node.name != n[0].name {
// if it's visited the graph is cyclical
if visited[edge.node.name] {
return true
}
stack.Push([2]*Node{n[1], edge.node})
}
}
}
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment