0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Python] BFS(幅優先探索) ABC168D

0
Last updated at Posted at 2020-12-06

ABC168D

連結グラフなので、BFSの原理から最小性が保障されることに注意する。
参考
BFS (幅優先探索) 超入門! 〜 キューを鮮やかに使いこなす 〜

サンプルコード
from collections import deque
# 頂点数と辺数
N, M = map(int, input().split())
# 辺
AB = [map(int, input().split()) for _ in range(M)]
# 無向グラフの隣接リスト設定
link = [[] for _ in range(N + 1)]
for a, b in AB:
  # aとbをそれぞれ紐付け
  link[a].append(b)
  link[b].append(a)
# BFSのデータフレーム
dist = [-1] * (N + 1) # 看板未設定
que = deque([1]) # 頂点1を始点とした訪問キュー
# BFS 開始 (キューが空になるまで探索を行う)
while que:
  v = que.popleft() # キューから先頭頂点(現在地)v取得
  for i in link[v]:
   # 未設定頂点iに現在地への看板を設定し訪問キューに追加する
   # 未設定頂点iに現在地への看板を設定し、iを訪問キューに追加する
   if dist[i] == -1:
     dist[i] = v
     que.append(i)

# 結果出力(各頂点に設置する看板)
print('Yes')
print('\n'.join(str(v) for v in dist[2:]))
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?