Skip to content

Commit 64a85f6

Browse files
authored
Update minimum-time-takes-to-reach-destination-without-drowning.py
1 parent 05c4525 commit 64a85f6

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

Python/minimum-time-takes-to-reach-destination-without-drowning.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ def minimumSeconds(self, land):
99
:rtype: int
1010
"""
1111
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
12-
lookup = [[0 if land[i][j] != "*" else -1 for j in xrange(len(land[0]))] for i in xrange(len(land))]
12+
lookup = [[-1 if land[i][j] == "*" else 0 for j in xrange(len(land[0]))] for i in xrange(len(land))]
1313
q = [(i, j, -1) for i in xrange(len(land)) for j in xrange(len(land[0])) if land[i][j] == "*"]
1414
q.append(next((i, j, 0) for i in xrange(len(land)) for j in xrange(len(land[0])) if land[i][j] == "S"))
1515
while q:
@@ -41,26 +41,28 @@ def minimumSeconds(self, land):
4141
:rtype: int
4242
"""
4343
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
44-
lookup = [[0 if land[i][j] != "*" else -1 for j in xrange(len(land[0]))] for i in xrange(len(land))]
44+
lookup1 = [[0 if land[i][j] == "*" else -1 for j in xrange(len(land[0]))] for i in xrange(len(land))]
45+
lookup2 = [[-1]*len(land[0]) for _ in xrange(len(land))]
4546
q1 = [(i, j) for i in xrange(len(land)) for j in xrange(len(land[0])) if land[i][j] == "*"]
46-
q2 = [next((i, j, 0) for i in xrange(len(land)) for j in xrange(len(land[0])) if land[i][j] == "S")]
47+
q2 = [next((i, j) for i in xrange(len(land)) for j in xrange(len(land[0])) if land[i][j] == "S")]
48+
lookup2[q2[0][0]][q2[0][1]] = 0
4749
while q1 or q2:
4850
new_q1, new_q2 = [], []
4951
for i, j in q1:
5052
for di, dj in DIRECTIONS:
5153
ni, nj = i+di, j+dj
52-
if not (0 <= ni < len(land) and 0 <= nj < len(land[0]) and land[ni][nj] != "X" and land[ni][nj] != "D" and lookup[ni][nj] != -1):
54+
if not (0 <= ni < len(land) and 0 <= nj < len(land[0]) and land[ni][nj] != "X" and land[ni][nj] != "D" and lookup1[ni][nj] == -1):
5355
continue
54-
lookup[ni][nj] = -1
56+
lookup1[ni][nj] = 0
5557
new_q1.append((ni, nj))
56-
for i, j, d in q2:
58+
for i, j in q2:
5759
if land[i][j] == "D":
58-
return d
60+
return lookup2[i][j]
5961
for di, dj in DIRECTIONS:
6062
ni, nj = i+di, j+dj
61-
if not (0 <= ni < len(land) and 0 <= nj < len(land[0]) and land[ni][nj] != "X" and lookup[ni][nj] == 0):
63+
if not (0 <= ni < len(land) and 0 <= nj < len(land[0]) and land[ni][nj] != "X" and lookup2[ni][nj] == lookup1[ni][nj] == -1):
6264
continue
63-
lookup[ni][nj] = 1
64-
new_q2.append((ni, nj, d+1))
65+
lookup2[ni][nj] = lookup2[i][j]+1
66+
new_q2.append((ni, nj))
6567
q1, q2 = new_q1, new_q2
6668
return -1

0 commit comments

Comments
 (0)