Skip to content

Commit d53719d

Browse files
Added steps-to-treasure-island
1 parent c764588 commit d53719d

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#https://ide.geeksforgeeks.org/vmx13r2tRM
2+
3+
#path to treasure island
4+
from collections import deque
5+
6+
#bfs
7+
def minimum_distance(island):
8+
if island is None or island == []: return 0
9+
10+
#all okay, lets begin
11+
steps = 0
12+
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] #left, right, up, down
13+
queue = deque() #to store directions
14+
rlen, clen, dirlen = len(island), len(island[0]), len(directions)
15+
visited = [[0] * rlen for _ in range(clen)]
16+
#print(visited)
17+
18+
queue.append((0, 0)) #start
19+
while queue:
20+
sz = len(queue)
21+
while sz > 0:
22+
x, y = queue.popleft() #get the co-ords of next in queue
23+
if island[x][y] == 'X': #found an obstacle, return condition for recursion
24+
return steps
25+
for i in range(dirlen): #find the deviations on basis of directions
26+
dx, dy = x + directions[i][0], y + directions[i][1]
27+
#check for edge-cases and if already explored
28+
if dx >= 0 and dy >= 0 and dx < rlen and dy < clen and (visited[dx][dy] == 0) and (island[dx][dy] == 'O' or island[dx][dy] == 'X'):
29+
visited[dx][dy] = 1
30+
queue.append((dx, dy))
31+
sz -= 1
32+
steps += 1
33+
34+
if __name__ == '__main__':
35+
island = [['O', 'O', 'O', 'O'],
36+
['D', 'O', 'D', 'O'],
37+
['O', 'O', 'O', 'O'],
38+
['O', 'D', 'X', 'O']]
39+
result = minimum_distance(island)
40+
print(result)
41+

0 commit comments

Comments
 (0)