Skip to content

Commit bc3684d

Browse files
committed
Snake and ladder problem.
1 parent 0b9728e commit bc3684d

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Interview-Questions/snake_n_ladder.rb

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
=begin
2+
3+
Rules The game is played with a cubic die of faces numbered to .
4+
5+
Starting from square , land on square with the exact roll of the die. If moving the number rolled would place the player beyond square , no move is made.
6+
7+
If a player lands at the base of a ladder, the player must climb the ladder. Ladders go up only.
8+
9+
If a player lands at the mouth of a snake, the player must go down the snake and come out through the tail. Snakes go down only.
10+
11+
Input:
12+
3
13+
32 62
14+
42 68
15+
12 98
16+
7
17+
95 13
18+
97 25
19+
93 37
20+
79 27
21+
75 19
22+
49 47
23+
67 17
24+
25+
=end
26+
27+
def quickest_way_up(ladders, snakes)
28+
h_snakes, h_ladders = {}, {}
29+
ladders.each do |ladder|
30+
h_ladders[ladder[0]] = ladder[1]
31+
end
32+
snakes.each do |snake|
33+
h_snakes[snake[0]] = snake[1]
34+
end
35+
adj_nodes = {}
36+
(0...100).each do |node|
37+
(node+1..node+6).each do |i|
38+
next_pos = h_ladders[i] || h_snakes[i] || i
39+
if(adj_nodes[node])
40+
adj_nodes[node] << next_pos if next_pos <= 100
41+
else
42+
adj_nodes[node] = [next_pos]
43+
end
44+
end
45+
end
46+
dist = {1 => 0}
47+
queue = [1]
48+
while(!queue.empty?)
49+
c_node = queue.shift
50+
adj_nodes[c_node].each do |neigh|
51+
if(!dist[neigh])
52+
queue.push(neigh) if neigh < 100
53+
dist[neigh] = dist[c_node] + 1
54+
return dist[neigh] if neigh == 100
55+
end
56+
end
57+
end
58+
return -1
59+
end
60+
61+
ladders = [[32,62], [42, 68], [12, 98]]
62+
snakes = [[95, 13], [97, 25], [93, 37], [79, 27], [75, 19], [49, 47], [67, 17]]
63+
p quickest_way_up(ladders, snakes)

0 commit comments

Comments
 (0)