-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathislandProbability.py
93 lines (75 loc) · 2.57 KB
/
islandProbability.py
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
__author__ = "Shashwat Tiwari"
__email__ = "shashwat1791@gmail.com"
"""
An island is represented in an 2d array of size mxn. If robot moves out of island it gets
destroyed and robot is allowed to move top, down, left, right. Given a robot position (x, y)
and k steps, what is the probability of robot getting survived in the effort of making
k steps.
"""
class Solution:
def __init__(self):
self.num_rows = 0
self.num_cols = 0
def check_validity_position(self, row, col):
if row >= 0 and row < self.num_rows and col >= 0 and col < self.num_cols:
return True
return False
def find_survival_probability(self, num_rows , num_cols , initial_position, number_of_steps):
"""
assuming island is zero indexed, example top left position will be considered (0,0)
"""
self.num_rows = num_rows
self.num_cols = num_cols
# hold valid moves
valid_moves = 0
# hold invalid moves
invalid_moves = 0
# we also assume that initial position robot is valid
# otherwise we will have to handle that edge case
bfs_queue = []
bfs_queue.append(initial_position)
# to store the end of level
bfs_queue.append((None,None))
while(len(bfs_queue)!=0 and number_of_steps > 0):
curr_row, curr_col = bfs_queue.pop(0)
if curr_row != None and curr_col != None:
# check right move
if(self.check_validity_position(curr_row, curr_col+1)):
valid_moves += 1
# if move is valid, enqueue the new valid move
bfs_queue.append((curr_row, curr_col+1))
else:
invalid_moves += 1
# check left move
if(self.check_validity_position(curr_row, curr_col-1)):
valid_moves += 1
# if move is valid, enqueue the new valid move
bfs_queue.append((curr_row, curr_col-1))
else:
invalid_moves += 1
# check top move
if(self.check_validity_position(curr_row-1, curr_col)):
valid_moves += 1
# if move is valid, enqueue the new valid move
bfs_queue.append((curr_row-1, curr_col))
else:
invalid_moves += 1
# check down move
if(self.check_validity_position(curr_row+1, curr_col)):
valid_moves += 1
# if move is valid, enqueue the new valid move
bfs_queue.append((curr_row+1, curr_col))
else:
invalid_moves += 1
else:
if(len(bfs_queue)!=0):
bfs_queue.append((None,None))
number_of_steps -= 1
total_moves = valid_moves + invalid_moves
# Debug
print((valid_moves, valid_moves+ invalid_moves))
probability = valid_moves/(invalid_moves+valid_moves)
return probability
if __name__ == "__main__":
testcase = Solution().find_survival_probability(3,3,(0,0), 2)
print(testcase)