Moving right along

This commit is contained in:
2019-12-18 07:25:25 -06:00
parent 0e315631dd
commit 629f47bcf9
7 changed files with 462 additions and 12 deletions

View File

@@ -104,11 +104,44 @@ func play(prog []int) {
}
}
}()
ret := p.Run()
if ret == intcode.RET_DONE {
maze.Print()
} else if ret == intcode.RET_ERR {
fmt.Println("ERROR")
fmt.Println(p.Error())
p.Run()
//We force quit the program when the maze is built.
// Now we find the quickest path through the maze.
fmt.Println(helpers.CLEAR_SCREEN)
maze.Print()
fmt.Println("Now find shortest path")
done, ret := BFS(maze.bfs[maze.startCoord], maze.bfs[maze.o2Coord])
if done {
fmt.Println("Found Route")
} else {
fmt.Println("No Route Found")
}
fmt.Println("Steps:", len(ret))
}
func BFS(start, goal *BFSNode) (bool, []*BFSNode) {
var queue, explored []*BFSNode
queue = append(queue, start)
if start == goal {
return true, queue
}
explored = append(explored, start)
for len(queue) > 0 {
var current *BFSNode
if len(queue) > 1 {
current, queue = queue[0], queue[1:]
if current == goal {
return true, explored
} else {
children := current.getChildren()
if len(children) != 0 {
queue = append(queue, children...)
} else {
return false, explored
}
}
}
explored = append(explored, current)
}
return false, explored
}

View File

@@ -28,22 +28,55 @@ type Maze struct {
path []*helpers.Coordinate
dirHistory []int
dnt bool
bfs map[*helpers.Coordinate]*BFSNode
startCoord *helpers.Coordinate
o2Coord *helpers.Coordinate
}
func NewMaze() *Maze {
m := &Maze{
maze: make(map[string]int),
maxX: helpers.MIN_INT,
minX: helpers.MAX_INT,
maxY: helpers.MIN_INT,
minY: helpers.MAX_INT,
bot: helpers.NewCoordinate(0, 0),
maze: make(map[string]int),
maxX: helpers.MIN_INT,
minX: helpers.MAX_INT,
maxY: helpers.MIN_INT,
minY: helpers.MAX_INT,
bot: helpers.NewCoordinate(0, 0),
bfs: make(map[*helpers.Coordinate]*BFSNode),
startCoord: helpers.NewCoordinate(0, 0),
}
m.path = append(m.path, helpers.NewCoordinate(0, 0))
return m
}
func (m *Maze) SetCoord(c *helpers.Coordinate, val int) {
var b *BFSNode
var ok bool
if b, ok = m.bfs[c]; !ok {
b = &BFSNode{Value: val}
m.bfs[c] = b
}
// Create the BFS node for this
if n, ok := m.bfs[c.GetNorthCoord()]; ok {
n.South = b
b.North = n
}
if e, ok := m.bfs[c.GetEastCoord()]; ok {
e.West = b
b.East = e
}
if s, ok := m.bfs[c.GetSouthCoord()]; ok {
s.North = b
b.South = s
}
if w, ok := m.bfs[c.GetWestCoord()]; ok {
w.East = b
b.West = w
}
if val == 2 {
m.o2Coord = c
}
m.maze[c.String()] = val
if m.maxX < c.X {
m.maxX = c.X
@@ -137,3 +170,26 @@ func (m *Maze) Print() {
fmt.Println()
}
}
type BFSNode struct {
Value int
North, East *BFSNode
South, West *BFSNode
}
func (b *BFSNode) getChildren() []*BFSNode {
var ret []*BFSNode
if b.North != nil {
ret = append(ret, b.North)
}
if b.East != nil {
ret = append(ret, b.East)
}
if b.South != nil {
ret = append(ret, b.South)
}
if b.West != nil {
ret = append(ret, b.West)
}
return ret
}