Skip to content

Instantly share code, notes, and snippets.

@maehrm
Created February 11, 2026 06:16
Show Gist options
  • Select an option

  • Save maehrm/2d0fdebbc26c59972f9fa20168ce3a1c to your computer and use it in GitHub Desktop.

Select an option

Save maehrm/2d0fdebbc26c59972f9fa20168ce3a1c to your computer and use it in GitHub Desktop.
from collections import deque
def bfs(x, k):
que = deque([(x, 0)])
visits = set([x])
while que:
cur, dist = que.popleft()
for nxt in G[cur]:
if nxt in visits:
continue
if dist < k:
que.append((nxt, dist + 1))
visits.add(nxt)
return sum(visits)
N, M = map(int, input().split())
G = [[] for _ in range(N + 1)]
for _ in range(M):
a, b = map(int, input().split())
G[a].append(b)
G[b].append(a)
Q = int(input())
for _ in range(Q):
x, k = map(int, input().split())
print(bfs(x, k))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment