-
Notifications
You must be signed in to change notification settings - Fork 0
/
pathfinder.rb
48 lines (39 loc) · 882 Bytes
/
pathfinder.rb
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
class PathFinder
attr_reader :paths
def initialize(grid_size)
@size = grid_size - 1
build_grid
@paths = 0
end
def explore(grid = @grid, coord = [0, 0])
@paths += 1 if coord == [@size, @size]
gridcopy = Marshal.load(Marshal.dump(grid))
gridcopy[coord] = false
possible_moves(coord).each { |move| explore(gridcopy, move) if gridcopy[move] }
@paths
end
private
def possible_moves(coord)
[up(coord), right(coord), down(coord), left(coord)]
end
def right(coord)
[coord.first + 1, coord.last]
end
def left(coord)
[coord.first - 1, coord.last]
end
def up(coord)
[coord.first, coord.last - 1]
end
def down(coord)
[coord.first, coord.last + 1]
end
def build_grid
@grid = Hash.new
(0..@size).each do |i|
(0..@size).each do |j|
@grid[[i, j]] = true
end
end
end
end