-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaze.go
399 lines (342 loc) · 8.18 KB
/
maze.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package main
import (
"image"
"image/color"
"image/color/palette"
"image/gif"
"math/rand"
"strings"
)
var (
red = color.RGBA{R: 255, A: 255}
blue = color.RGBA{B: 255, A: 255}
green = color.RGBA{G: 255, A: 255}
black = color.RGBA{0, 0, 0, 0}
white = color.RGBA{255, 255, 255, 255}
yellow = color.RGBA{255, 255, 102, 255}
)
func DFS(stack *stack, seed int64) func(*Maze) (*Maze, []*cell) {
return func(m *Maze) (*Maze, []*cell) {
rand.Seed(seed)
genPath := make([]*cell, 0, m.w*m.h)
current := m.Begin()
current.visited = true
filter := func(c *cell) bool {
return !c.visited
}
for {
unvisited := m.AdjacentCells(current, filter)
if len(unvisited) > 0 {
genPath = append(genPath, current)
next := unvisited[rand.Intn(len(unvisited))]
stack.Push(current)
m.RmWall(current, next)
current = next
current.visited = true
} else if stack.Len() > 0 {
current = stack.Pop()
} else {
break
}
}
return m, genPath
}
}
// returns path and all visited cells
// DFS recur search
func FindPath(m *Maze, start, end *cell, path, visited *[]*cell) bool {
if start.visited {
return false
}
start.visited = true
*path = append(*path, start)
*visited = append(*visited, start)
if start == end {
return true
}
//filter connected cells
unvisited := m.AdjacentCells(start, func(c *cell) bool {
return isConnected(start, c) && !c.visited
})
for _, next := range unvisited {
if FindPath(m, next, end, path, visited) {
return true
}
}
// cell is not part of path
*path = (*path)[:len(*path)-1]
return false
}
// returns path and all visited cells
// BFS search with storing dist for each cell from start point
func FindShortestPath(m *Maze, start, end *cell, path, visited *[]*cell) bool {
q := make([]*cell, 0, 4)
start.visited = true
*visited = append(*visited, start)
current := start
// store distance from start point
visitedCellDist := make(map[*cell]int)
stepsFromStart := 0
for {
//filter connected, not visited cells
unvisited := m.AdjacentCells(current, func(c *cell) bool {
return isConnected(current, c) && !c.visited
})
stepsFromStart++
// check all connected cells
for _, c := range unvisited {
c.visited = true
q = append(q, c)
*visited = append(*visited, c)
// store dist
visitedCellDist[c] = stepsFromStart
if c != end {
continue
}
// found end point
// compute shortest path backwards
min := 1<<31 - 1
for {
// add cell to shortest path
*path = append(*path, c)
if c == start {
break
}
// get all connected and visited cells
connected := m.AdjacentCells(c, func(c2 *cell) bool {
return isConnected(c, c2) && c2.visited
})
// find cell which is closest to start point
for _, next := range connected {
if dist := visitedCellDist[next]; min > dist {
c = next
min = dist
}
}
}
return true
}
if len(q) > 0 {
current = q[0]
q[0] = nil
q = q[1:]
} else {
break
}
}
return false
}
type point struct {
x, y int
}
type cell struct {
left, up, right, down bool // doors if exits
visited bool
point
}
type Maze struct {
w, h int
entry, exit point
cells [][]*cell
}
// remove adjacent cells walls
func (m *Maze) RmWall(cell1, cell2 *cell) {
dx := cell1.x - cell2.x
dy := cell1.y - cell2.y
// panic if cell not adjacent or same
if dx+dy == 0 || dx+dy > 1 || dx+dy < -1 {
panic("cells not adjacent or same")
}
switch {
case dx > 0:
// left wall
cell1.left = true
cell2.right = true
case dx < 0:
// right wall
cell1.right = true
cell2.left = true
case dy > 0:
// up wall
cell1.up = true
cell2.down = true
case dy < 0:
// down wall
cell1.down = true
cell2.up = true
default:
panic("bug")
}
}
// return adjecent filtered cells
func (m *Maze) AdjacentCells(c *cell, filter func(*cell) bool) []*cell {
p := c.point
cells := []*cell{}
data := []struct {
cond bool
point
}{
{p.x > 0, point{p.x - 1, p.y}},
{p.x < m.w-1, point{p.x + 1, p.y}},
{p.y > 0, point{p.x, p.y - 1}},
{p.y < m.h-1, point{p.x, p.y + 1}},
}
for _, d := range data {
if d.cond && filter(m.cells[d.x][d.y]) {
cells = append(cells, m.cells[d.x][d.y])
}
}
return cells
}
func isConnected(c1, c2 *cell) bool {
if c1.y+1 == c2.y && c2.up && c1.down ||
c1.x-1 == c2.x && c2.right && c1.left ||
c1.y-1 == c2.y && c2.down && c1.up ||
c1.x+1 == c2.x && c2.left && c1.right {
return true
}
return false
}
func NewMaze(w, h int, entry, exit point,
generator func(*Maze) (*Maze, []*cell)) (*Maze, []*cell) {
if w < 1 || h < 1 {
panic("w, h should be > 1")
}
for _, p := range []point{entry, exit} {
if p.x > w-1 || p.x < 0 || p.y > h-1 || p.y < 0 {
panic("start and end point should be inside maze")
}
}
m := &Maze{w: w, h: h, entry: entry, exit: exit, cells: make([][]*cell, w)}
for x := range m.cells {
if m.cells[x] == nil {
m.cells[x] = make([]*cell, h)
}
for y := range m.cells[x] {
m.cells[x][y] = &cell{point: point{x, y}}
}
}
if generator == nil {
return m, nil
}
return generator(m)
}
func (m *Maze) ResetVisitedCells() {
for x := range m.cells {
for y := range m.cells[x] {
m.cells[x][y].visited = false
}
}
}
func (m *Maze) Begin() *cell {
return m.cells[m.entry.x][m.entry.y]
}
func (m *Maze) End() *cell {
return m.cells[m.exit.x][m.exit.y]
}
func (m *Maze) String() string {
output, hline, vline := []byte{}, []byte{}, []byte{}
for y := 0; y < m.h; y++ {
for x := 0; x < m.w; x++ {
mark := " "
if x == m.entry.x && y == m.entry.y {
mark = "S"
}
if x == m.exit.x && y == m.exit.y {
mark = "E"
}
hElm := "+---"
vElm := "| " + mark + " "
if m.cells[x][y].up {
hElm = "+ "
}
if m.cells[x][y].left {
vElm = " " + mark + " "
}
hline = append(hline, []byte(hElm)...)
vline = append(vline, []byte(vElm)...)
}
output = append(output, append(hline, []byte("+\n")...)...)
output = append(output, append(vline, []byte("|\n")...)...)
hline, vline = hline[:0], vline[:0]
}
return strings.Join([]string{string(output), strings.Repeat("+---", m.w), "+\n"}, "")
}
func Draw(m *Maze, fill, border color.Color, cw, ch, ww int) *image.Paletted {
r := image.Rect(0, 0, m.w*cw, m.h*cw)
img := image.NewPaletted(r, palette.WebSafe)
for y := 0; y < m.h; y++ {
for x := 0; x < m.w; x++ {
cell := m.cells[x][y]
rect := image.Rect(cell.x*cw, cell.y*ch, cell.x*cw+cw, cell.y*ch+ch)
DrawCell(cell, img.SubImage(rect).(*image.Paletted), fill, border, cw, ch, ww)
}
}
return img
}
func DrawCell(cell *cell, img *image.Paletted,
fill, border color.Color,
cw, ch, ww int) {
rect := img.Bounds()
x0, y0, x1, y1 := rect.Min.X, rect.Min.Y, rect.Max.X, rect.Max.Y
for y := y0; y < y1; y++ {
for x := x0; x < x1; x++ {
img.Set(x, y, fill)
// check walls
if (!cell.left && x < x0+ww) ||
(!cell.right && x > x1-ww) ||
(!cell.up && y < y0+ww) ||
(!cell.down && y > y1-ww) {
img.Set(x, y, border)
}
}
}
}
// speed in 100th of second
func AnimatePath(m *Maze, visited, path []*cell,
fillVis, fillPath, border color.Color,
cw, ch, ww, speed int) *gif.GIF {
r := image.Rect(0, 0, m.w*cw, m.h*ch)
img := image.NewPaletted(r, palette.WebSafe)
imgs := []image.Image{img}
lenVisited := len(visited)
// join visited and path cells
visited = append(visited, path...)
for i, cell := range visited {
fill := fillVis
rect := image.Rect(cell.x*cw, cell.y*ch, cell.x*cw+cw, cell.y*ch+ch)
cellImg := image.NewPaletted(rect, palette.WebSafe)
if i >= lenVisited {
fill = fillPath // fill path diff
}
DrawCell(cell, cellImg, fill, border, cw, ch, ww)
imgs = append(imgs, cellImg)
}
gifAnim := &gif.GIF{
Image: make([]*image.Paletted, len(imgs)),
Delay: make([]int, len(imgs)),
LoopCount: -1,
}
for i := range imgs {
gifAnim.Image[i] = imgs[i].(*image.Paletted)
gifAnim.Delay[i] = speed
}
return gifAnim
}
type stack struct {
cells []*cell
}
func NewStack() *stack {
return &stack{make([]*cell, 0, 10)}
}
func (s *stack) Push(c *cell) {
s.cells = append(s.cells, c)
}
func (s *stack) Pop() *cell {
c := s.cells[len(s.cells)-1]
s.cells = s.cells[:len(s.cells)-1]
return c
}
func (s *stack) Len() int {
return len(s.cells)
}