move = (0, 1), (1, 0), (0, -1), (-1, 0) classSolution: defcutOffTree(self, forest: List[List[int]]) -> int: road = [] for i inrange(0,len(forest)): for j inrange(0,len(forest[0])): if forest[i][j] == 0or forest[i][j] == 1: continue road.append([forest[i][j],i,j]) defmycmp(a,b): # 完全不需要,只是加深一下python3传自己的compare函数方法的记忆。 return a[0] - b[0] road.sort(key=functools.cmp_to_key(mycmp)) # 要用key=functools.cmp_to_key() ans = 0 if forest[0][0] == 0: return -1
defbfs(start, end): q = deque([(start, 0)]) vis = [list(r) for r in forest] while q: cur, step = q.popleft() if cur == end: return step x, y = cur step += 1 for dx, dy in move: if0 <= (nx := x + dx) < len(forest) and0 <= (ny := y + dy) < len(forest[0]) and vis[nx][ny]: vis[nx][ny] = 0 q.append(((nx, ny), step)) return -1
if road[0][1] != 0or road[0][2] != 0: ans = bfs((0,0),(road[0][1],road[0][2])) if ans == -1: return -1 for i inrange(1,len(road)): tmp = bfs((road[i-1][1],road[i-1][2]),(road[i][1],road[i][2])) # 点对之间找 if tmp == -1: return tmp ans += tmp return ans