Skip to content

Instantly share code, notes, and snippets.

@mrampton
Created May 11, 2018 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrampton/9e42b1bfb328b150a9343206ff09484c to your computer and use it in GitHub Desktop.
Save mrampton/9e42b1bfb328b150a9343206ff09484c to your computer and use it in GitHub Desktop.
class PathFinder
def initialize(maze, start_pos=nil, end_pos=nil)
@maze = maze # NxN, [row][col]
@visited_pos = {} # pos => entry_pos
@start_pos = (start_pos || [0,0])
@end_pos = (end_pos || [@maze.length - 1 , @maze[0].length - 1])
end
def find_path
current_pos = nil
entry_pos = [nil,nil]
pos_queue = [ { :pos => @start_pos, :entry => entry_pos } ]
while current_pos = pos_queue.shift
@visited_pos[current_pos[:pos]] = current_pos[:entry]
if current_pos[:pos] == @end_pos
break
end
neighbors = find_neighbors(current_pos[:pos])
neighbors.each do |neighbor|
pos_queue << { :pos => neighbor, :entry => current_pos[:pos] }
end
entry_pos = current_pos[:pos]
end
rebuild_path(current_pos[:pos])
end
private
def rebuild_path(pos)
path = [pos]
while pos != @start_pos
pos = @visited_pos[pos]
path.unshift pos
end
path
end
def find_neighbors(pos)
neighbors = []
row, col = pos
query_positions = [
[row - 1, col],
[row + 1, col],
[row, col - 1],
[row, col + 1]
]
query_positions.each do |r, c|
if (r < 0 || c < 0 || r == @maze.length || c == @maze[0].length)
next
end
# add if neighbor is an open path, and has not been visited
if @maze[r][c] == "1" && @visited_pos[[r,c]].nil?
neighbors << [r,c]
end
end
neighbors
end
end
@mrampton
Copy link
Author

Use docker:
docker run vividfarmer/armory:mazerunner

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment