Skip to content

Instantly share code, notes, and snippets.

@mikezter
Created August 24, 2016 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikezter/e00db1fd3365d3a73be4d5a57b18adf7 to your computer and use it in GitHub Desktop.
Save mikezter/e00db1fd3365d3a73be4d5a57b18adf7 to your computer and use it in GitHub Desktop.
read a buffer, make a tree, calculate distance of all other nodes from start-node
package main
import (
"bytes"
"fmt"
"io"
"os"
)
var sample = []byte(`2
4 2
1 2
1 3
1
3 1
2 3
2
`)
type node map[int]bool
type tree map[int]node
type distances map[int]int
const weight = 6
var dists distances
var visited node
var queue []int
func main() {
data := io.Reader(os.Stdin)
//
data = bytes.NewBuffer(sample2)
var q int
fmt.Fscan(data, &q)
for i := 0; i < q; i++ {
answerQuery(data)
fmt.Println()
}
// fmt.Println(expected2)
}
func answerQuery(data io.Reader) {
n, t := readGraph(data)
// fmt.Println(t)
var start int
fmt.Fscan(data, &start)
visited = node{}
dists = distances{}
searchGraph(t, start, 0)
for i := 1; i <= n; i++ {
if i == start {
continue
}
if dists[i] == 0 {
fmt.Print("-1 ")
} else {
fmt.Print(dists[i], " ")
}
}
}
func searchGraph(t tree, start, dist int) {
visited[start] = true
dists[start] = dist
newDist := dist + weight
for id, _ := range t[start] {
if visited[id] {
continue
}
oldDist, ok := dists[id]
if !ok || oldDist > newDist {
dists[id] = newDist
}
queue = append(queue, id)
}
if len(queue) == 0 {
return
}
id := queue[0]
queue = queue[1:]
searchGraph(t, id, dists[id])
}
func readGraph(data io.Reader) (int, tree) {
var n, m int
fmt.Fscan(data, &n, &m)
// fmt.Println(n, m)
t := make(tree, m)
var x, y int
for i := 0; i < m; i++ {
fmt.Fscan(data, &x, &y)
// fmt.Println(x, y)
t = addEdge(x, y, t)
}
return n, t
}
func addEdge(x, y int, t tree) tree {
if _, ok := t[x]; !ok {
t[x] = node{}
}
if _, ok := t[y]; !ok {
t[y] = node{}
}
t[x][y] = true
t[y][x] = true
return t
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment