hamilton/hamilton.go

94 lines
1.6 KiB
Go
Raw Normal View History

2021-06-10 21:27:25 +02:00
package main
import (
"fmt"
"os"
)
var g [][]int = [][]int{
[]int{1},
[]int{0, 2},
[]int{1, 3},
[]int{2, 4},
[]int{3, 5},
[]int{4, 6, 14},
[]int{5, 7},
[]int{6, 8, 14},
[]int{7, 9, 13},
[]int{8, 10, 12},
[]int{9, 11},
[]int{10, 12, 15},
[]int{9, 11, 13, 16},
[]int{8, 12, 14, 17},
[]int{5, 7, 13},
[]int{11, 16},
[]int{12, 15, 17},
[]int{13, 16},
}
var step int
func writeGraphfile(g [][]int, path []int) {
filename := fmt.Sprintf("step%07d.dot", step)
f, _ := os.Create(filename)
2021-06-10 23:15:54 +02:00
defer f.Close()
2021-06-10 21:27:25 +02:00
step++
fmt.Fprintln(f, "digraph {")
fmt.Fprintln(f, "dpi=200")
fmt.Fprintln(f, "node [shape=circle, style=filled, label=\"\"]")
for v1, adjlist := range g {
for _, v2 := range adjlist {
fmt.Fprintln(f, v1, " -> ", v2)
}
}
for i, _ := range g {
fmt.Fprintln(f, i, "[xlabel=x]")
}
for i, v := range path {
fmt.Fprintln(f, v, "[xlabel=", i, "]")
fillcolor := "red"
if i == 0 {
fillcolor = "blue"
} else if i == len(path)-1 {
fillcolor = "yellow"
}
fmt.Fprintln(f, v, "[fillcolor=", fillcolor, "]")
}
fmt.Fprintln(f, "}")
}
func contains(path []int, v int) bool {
for _, w := range path {
if w == v {
return true
}
}
return false
}
func DFS(g [][]int, path []int) {
deadend := true
for _, v2 := range g[path[len(path)-1]] {
if contains(path, v2) {
continue
}
deadend = false
path2 := append(path, v2)
DFS(g, path2)
}
if len(path) == len(g) {
fmt.Println("Found path: ", path)
writeGraphfile(g, path)
os.Exit(0)
} else if deadend {
writeGraphfile(g, path)
}
}
func main() {
step = 0
writeGraphfile(g, []int{})
DFS(g, []int{0})
os.Exit(-1)
}