# 小华和小为是很好朋友,她们约定周末去一起吃饭,通过手机交流,她们选择了很多聚集地点 # 由于自然地理地形等原因,部分聚餐地点不可达,求小华和小为都能到达的聚餐地点有多少个 # # 输入 # 第一行输入m,n m表示地图的长度,n表示地图的宽度 # 第二行开始输入具体信息,地图信息0表示畅通道路,1为障碍物 # 2为小华或小为 ,地图中仅有2个2,3为选中聚餐地点 # 4 4 # 2 1 0 3 # 0 1 2 1 # 0 3 0 0 # 0 0 0 0 # #输出: 2 from collections import deque def bfs(row, col): queue = deque([(row, col)]) visited = set([(row, col)]) while queue: r, c = queue.popleft() if (r, c) == end_spot: return True for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]: nr, nc = r + dr, c + dc if not (0 <= nr < m and 0 <= nc < n) or map_[nr][nc] == "1": continue if (nr, nc) not in visited: queue.append((nr, nc)) visited.add((nr, nc)) return False n, m = map(int, input().split()) map_ = [input().split() for _ in range(m)] start_spots = [] end_spots = [] for i in range(m): for j in range(n): if map_[i][j] == "2": start_spots.append((i, j)) elif map_[i][j] == "3": end_spots.append((i, j)) count = 0 for end_spot in end_spots: if all(bfs(start_spot[0], start_spot[1]) for start_spot in start_spots): count += 1 print(count)
29.聚餐地点 or 欢乐的周末-双端队列--OD
于 2024-03-24 16:02:07 首次发布