Last active
July 22, 2019 00:37
-
-
Save douglasmakey/cf727b3c7c7b8bf4daae0a6c29987f77 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
type edge struct { | |
node string | |
weight int | |
} | |
type graph struct { | |
nodes map[string][]edge | |
} | |
func newGraph() *graph { | |
return &graph{nodes: make(map[string][]edge)} | |
} | |
func (g *graph) addEdge(origin, destiny string, weight int) { | |
g.nodes[origin] = append(g.nodes[origin], edge{node: destiny, weight: weight}) | |
g.nodes[destiny] = append(g.nodes[destiny], edge{node: origin, weight: weight}) | |
} | |
func (g *graph) getEdges(node string) []edge { | |
return g.nodes[node] | |
} | |
func (g *graph) getPath(origin, destiny string) (int, []string) { | |
h := newHeap() | |
h.push(path{value: 0, nodes: []string{origin}}) | |
visited := make(map[string]bool) | |
for len(*h.values) > 0 { | |
// Find the nearest yet to visit node | |
p := h.pop() | |
node := p.nodes[len(p.nodes)-1] | |
if visited[node] { | |
continue | |
} | |
if node == destiny { | |
return p.value, p.nodes | |
} | |
for _, e := range g.getEdges(node) { | |
if !visited[e.node] { | |
// We calculate the total spent so far plus the cost and the path of getting here | |
h.push(path{value: p.value + e.weight, nodes: append([]string{}, append(p.nodes, e.node)...)}) | |
} | |
} | |
visited[node] = true | |
} | |
return 0, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment