-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaze.rb
126 lines (113 loc) · 2.08 KB
/
maze.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
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
# Author: Samir Undavia
class Maze
def initialize n,m
@n = n
@m = m
end
def load arg
@maze = arg
end
def display
row = 0
([email protected]).each do |i|
if i % @n == 0 && i != 0
puts
row += 1
end
if row.odd? && @maze[i] == '1'
print '|'
elsif row.even? && @maze[i] == '1'
if i.even?
print '+'
else
print '-'
end
elsif @maze[i] == '0'
print ' '
end
end
end
def get_adjacent_openings index
adj = []
if @maze[index - @n] == '0'
adj.push index - @n
end
if @maze[index + @n] == '0'
adj.push index + @n
end
if @maze[index - 1] == '0'
adj.push index - 1
end
if @maze[index + 1] == '0'
adj.push index + 1
end
adj
end
def solve begX, begY, endX, endY
begI = begY*@n + begX
endI = endY*@n + endX
v = []
q = []
q.push begI
while !q.empty?
currentI = q.pop
return true if currentI == endI
get_adjacent_openings(currentI).each do |x|
if !v.include? x
q.push x
v.push x
end
end
end
return false
end
def trace begX, begY, endX, endY
begI = begY*@n + begX
endI = endY*@n + endX
v = []
q = []
solutionVisited = []
q.push begI
while !q.empty?
currentI = q.pop
solutionVisited.push currentI
return solutionVisited if currentI == endI
get_adjacent_openings(currentI).each do |x|
if !v.include? x
q.push x
v.push x
end
end
end
return false
end
def redesign
string=""
(0...@n).each {string+= "1"}
(0...(@n-2)).each {|x| string += "1" + (x % 2 == 0 ? genEvenRan : genOddRan) + "1"}
(0...@n).each {string+= "1"}
m = Maze.new @m, @n
m.load string
m.display
end
def genEvenRan
string=""
(0...(@m-2)).each {|x| string += (x % 2 == 0 ? "0" : rand(2).to_s)}
string
end
def genOddRan
string=""
(0...(@m-2)).each {|x| string += rand(2).to_s}
string
end
end
maz = Maze.new 9,9
maz.load "111111111100010001111010101100010101101110101100000101111011101100000101111111111"
maz.display
puts
puts maz.solve 1, 1, 7, 7
puts
puts "indexes visited: " + (maz.trace 1, 1, 7, 7).to_s
puts
puts "Redesigned maze"
maz.redesign