@@ -13,7 +13,6 @@ def minCost(self, grid):
13
13
"""
14
14
directions = [(0 , 1 ), (0 , - 1 ), (1 , 0 ), (- 1 , 0 )]
15
15
def a_star (grid , b , t ):
16
- R , C = len (grid ), len (grid [0 ])
17
16
f , dh = 0 , 1
18
17
closer , detour = [b ], []
19
18
lookup = set ()
@@ -29,7 +28,7 @@ def a_star(grid, b, t):
29
28
lookup .add (b )
30
29
for nd , (dr , dc ) in enumerate (directions , 1 ):
31
30
nb = (b [0 ]+ dr , b [1 ]+ dc )
32
- if not (0 <= nb [0 ] < R and 0 <= nb [1 ] < C and nb not in lookup ):
31
+ if not (0 <= nb [0 ] < len ( grid ) and 0 <= nb [1 ] < len ( grid [ 0 ]) and nb not in lookup ):
33
32
continue
34
33
(closer if nd == grid [b [0 ]][b [1 ]] else detour ).append (nb )
35
34
return - 1
@@ -47,25 +46,22 @@ def minCost(self, grid):
47
46
:rtype: int
48
47
"""
49
48
directions = [(0 , 1 ), (0 , - 1 ), (1 , 0 ), (- 1 , 0 )]
50
- R , C = len (grid ), len (grid [0 ])
51
- b , t = (0 , 0 ), (R - 1 , C - 1 )
49
+ b , t = (0 , 0 ), (len (grid )- 1 , len (grid [0 ])- 1 )
52
50
dq = collections .deque ([(b , 0 )])
53
- lookup = { b : 0 }
51
+ lookup = set ()
54
52
while dq :
55
53
b , d = dq .popleft ()
56
54
if b == t :
57
55
return d
58
- if lookup [ b ] < d :
56
+ if b in lookup :
59
57
continue
58
+ lookup .add (b )
60
59
for nd , (dr , dc ) in enumerate (directions , 1 ):
61
60
nb = (b [0 ]+ dr , b [1 ]+ dc )
62
- cost = 1 if nd != grid [b [0 ]][b [1 ]] else 0
63
- if not (0 <= nb [0 ] < R and 0 <= nb [1 ] < C and
64
- (nb not in lookup or lookup [nb ] > d + cost )):
61
+ if not (0 <= nb [0 ] < len (grid ) and 0 <= nb [1 ] < len (grid [0 ]) and nb not in lookup ):
65
62
continue
66
- lookup [nb ] = d + cost
67
- if not cost :
63
+ if nd == grid [b [0 ]][b [1 ]]:
68
64
dq .appendleft ((nb , d ))
69
65
else :
70
- dq .append ((nb , d + cost ))
66
+ dq .append ((nb , d + 1 ))
71
67
return - 1 # never reach here
0 commit comments