-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
113 lines (92 loc) · 2.08 KB
/
main.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
package main
import (
"errors"
"fmt"
"os"
"sync"
)
const (
up = iota
right
down
left
)
var posChan = make(chan position)
var doneChan = make(chan []string)
var mutex sync.Mutex
var visited = make(map[string][]string)
func main() {
filename := os.Args[1]
maze := createMaze(filename)
startPosition := maze.findStartPosition()
visited[startPosition.String()] = append(visited[startPosition.String()], startPosition.String())
sendScoutsToAllDirections(startPosition, maze)
for {
select {
case position := <-posChan:
if position.isEmpty(maze) {
sendScoutsToAllDirections(position, maze)
}
case finalRoute := <-doneChan:
fmt.Println(finalRoute)
return
}
}
}
func sendScoutsToAllDirections(from position, maze mazeType) {
if to, err := canMove(up, from, maze); err == nil {
go move(from, to, maze)
}
if to, err := canMove(right, from, maze); err == nil {
go move(from, to, maze)
}
if to, err := canMove(down, from, maze); err == nil {
go move(from, to, maze)
}
if to, err := canMove(left, from, maze); err == nil {
go move(from, to, maze)
}
}
func move(from, to position, maze mazeType) {
mutex.Lock()
visited[to.String()] = append(visited[from.String()], to.String())
mutex.Unlock()
if to.getValue(maze) == mazeFinish {
doneChan <- visited[to.String()]
} else {
sendScoutsToAllDirections(to, maze)
}
}
func canMove(direction int, current position, maze mazeType) (position, error) {
var newX, newY int
switch direction {
case up:
newX, newY = current.x+1, current.y
case right:
newX, newY = current.x, current.y+1
case down:
newX, newY = current.x-1, current.y
case left:
newX, newY = current.x, current.y-1
}
newPosition := position{
newX,
newY,
}
if newPosition.outOfBounds(maze) {
return position{}, errors.New("OutOfBounds")
}
if newPosition.isWall(maze) {
return position{}, errors.New("Wall")
}
if newPosition.isVisited() {
return position{}, errors.New("Visited")
}
return newPosition, nil
}
func (p *position) isVisited() bool {
mutex.Lock()
_, ok := visited[p.String()]
mutex.Unlock()
return ok
}