enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,
同时列出数据和数据下标,一般用在 for 循环当中
class Solution(object):
def uniquePathsIII(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
R, C = len(grid), len(grid[0])
self.res = 0
todo = 0
for r, row in enumerate(grid):
for c, v in enumerate(row):
if v != -1:
todo += 1
if v == 1:
sr, sc = r, c
if v == 2:
tr, tc = r, c
def neighbors(r, c):
for nr, nc in ((r-1, c),(r, c-1),(r+1, c),(r, c+1)):
if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] % 2 == 0:
yield nr, nc
def dfs(r, c, todo):
todo -= 1
if todo < 0:
return
if r == tr and c == tc:
if todo == 0:
self.res += 1
return
grid[r][c] = -1
for nr, nc in neighbors(r, c):
dfs(nr, nc, todo)
grid[r][c] = 0
dfs(sr, sc, todo)
return self.res