-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexample2_test.go
109 lines (95 loc) · 2.29 KB
/
example2_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Copyright 2018 Frederik Zipp. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package astar_test
import (
"fmt"
"image"
"iter"
"math"
"github.com/fzipp/astar"
)
func ExampleFindPath_maze() {
maze := floorPlan{
"###############",
"# # # # #",
"# ### ### ### #",
"# # # # # #",
"### # # # ### #",
"# # # #",
"# # ### ### ###",
"# # # # # #",
"### # # # # ###",
"# # # # #",
"# # ######### #",
"# # #",
"# ### # # ### #",
"# # # # #",
"###############",
}
start := image.Pt(1, 13) // Bottom left corner
dest := image.Pt(13, 1) // Top right corner
// Find the shortest path
path := astar.FindPath[image.Point](maze, start, dest, distance, distance)
// Mark the path with dots before printing
for _, p := range path {
maze.put(p, '.')
}
maze.print()
// Output:
// ###############
// # # # #.#
// # ### ### ###.#
// # # # # #.#
// ### # # # ###.#
// # # # .......#
// # # ###.### ###
// # # #.# # #
// ### # #.# # ###
// # #..... # # #
// # #.######### #
// #... # #
// #.### # # ### #
// #. # # # #
// ###############
}
// distance is our cost function. We use points as nodes, so we
// calculate their Euclidean distance.
func distance(p, q image.Point) float64 {
d := q.Sub(p)
return math.Sqrt(float64(d.X*d.X + d.Y*d.Y))
}
type floorPlan []string
var offsets = [...]image.Point{
image.Pt(0, -1), // North
image.Pt(1, 0), // East
image.Pt(0, 1), // South
image.Pt(-1, 0), // West
}
// Neighbours implements the astar.Graph[Node] interface (with Node = image.Point).
func (f floorPlan) Neighbours(p image.Point) iter.Seq[image.Point] {
return func(yield func(image.Point) bool) {
for _, off := range offsets {
q := p.Add(off)
if f.isFreeAt(q) {
if !yield(q) {
return
}
}
}
}
}
func (f floorPlan) isFreeAt(p image.Point) bool {
return f.isInBounds(p) && f[p.Y][p.X] == ' '
}
func (f floorPlan) isInBounds(p image.Point) bool {
return (0 <= p.X && p.X < len(f[p.Y])) && (0 <= p.Y && p.Y < len(f))
}
func (f floorPlan) put(p image.Point, c rune) {
f[p.Y] = f[p.Y][:p.X] + string(c) + f[p.Y][p.X+1:]
}
func (f floorPlan) print() {
for _, row := range f {
fmt.Println(row)
}
}