# 输入: # 3 # 0 1 # 0 2 # 输出:yes # # 输入: # 2 # 1 0 # 0 1 # 输出:no # 5 # 4 3 # 0 4 # 2 1 # 3 2 # 输出:yes # 地上共有N个格子,你需要跳完地上所有格子,但是格子间是有强依赖关系的,跳完前一个格子后,后续的格子才会被开启, # 格子间的依赖关系由多组steps数组给出,step[0]表示前一个格子,steps[1]表示steps[0]可以开启的格子; # 比如[0,1]表示从跳完第0个格子以后第1个格子就开启了,比如[0,1]表示从跳完第0个格子以后,第1个格子就开启 # 比如[2,1],[2,3]表示跳完第2个格子后第1个格子和第3个格子就被开启了 # 请你计算是否能由给出的steps数组跳完所有的格子,如果可以输出yes,否则输出no # 说明: # 1、你可以从一个格子跳到任意一个开启的格子 # 2、没有前置依赖的格子默认是开启的 # 3、如果总数是N,则所有的格子编号为[0,1,2,3……N-1]连续的数组 # # 输入一个整数N表示总共多少个格子,接着输入多组二维数组steps表示所有格子之间的依赖关系 # # 输出:如果能按照stpes给定的依赖顺序跳完所有的格子输出yes # 否则输出no from typing import List def skip_grid(n: int, grids: List[List[int]]) -> bool: x = [None] * n map = {} for i in range(len(grids)): a = grids[i] if a[0] not in map: map[a[0]] = [] map[a[0]].append(a[1]) x[a[1]] = a[0] print("x=", x) print("map=",map) stack = [] for i in range(n): if x[i] is None: stack.append(i) if not stack: return False while stack: index = stack.pop() x[index] = -1 if index not in map.keys(): continue for item in map[index]: if x[item] != -1: stack.append(item) return all(val == -1 for val in x) if __name__ == '__main__': # 数据固定了 n = 2 grids = [[1, 0], [0, 1]] n = int(input()) grids = [] while True: line = input().split(' ') if line[0]: grids.append(list(map(int, line))) else: break r = skip_grid(n, grids) print("yes" if r else "no")
43.跳格子1--难点
最新推荐文章于 2025-03-11 11:41:22 发布