Skip to content

Instantly share code, notes, and snippets.

type Node struct {
name string
value int
}
type Edge struct {
node *Node
weight int
}
package main
import (
"fmt"
"math"
"os"
"strconv"
"sync"
)
@sausheong
sausheong / main.go
Last active March 20, 2022 03:06
da
func main() {
// build and run Dijkstra's algorithm on graph
graph := buildGraph()
city := os.Args[1]
dijkstra(graph, city)
// display the nodes
for _, node := range graph.Nodes {
fmt.Printf("Shortest time from %s to %s is %d\n",
city, node.name, node.value)
func dijkstra(graph *WeightedGraph, city string) {
visited := make(map[string]bool)
heap := &Heap{}
startNode := graph.GetNode(city)
startNode.value = 0
heap.Push(startNode)
for heap.Size() > 0 {
current := heap.Pop()
func buildGraph() *WeightedGraph {
graph := NewGraph()
nodes := AddNodes(graph,
"London",
"Paris",
"Amsterdam",
"Luxembourg",
"Zurich",
"Rome",
"Berlin",
type Heap struct {
elements []*Node
mutex sync.RWMutex
}
func (h *Heap) Size() int {
h.mutex.RLock()
defer h.mutex.RUnlock()
return len(h.elements)
}
func (g *WeightedGraph) GetNode(name string) (node *Node) {
g.mutex.RLock()
defer g.mutex.RUnlock()
for _, n := range g.Nodes {
if n.name == name {
node = n
}
}
return
}
func NewGraph() *WeightedGraph {
return &WeightedGraph{
Edges: make(map[string][]*Edge),
}
}
type Node struct {
name string
value int
through *Node
}
type Edge struct {
node *Node
weight int
}
@sausheong
sausheong / heap4.go
Last active March 19, 2022 00:46
ds
func parent(i int) int {
return (i - 1) / 2
}
func leftChild(i int) int {
return 2*i + 1
}
func rightChild(i int) int {
return 2*i + 2