Problem:
Breadth First Search Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$. Input In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format: $u$ $k$ $v_1$ $v_2$ ... $v_k$ $u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$. Constraints  $1 \leq n \leq 100$  Output For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs. Sample Input 1 4
1 2 2 4
2 1 4
3 0
4 1 3 Sample Output 1 1 0
2 1
3 2
4 1 Reference Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution (Python):
from collections import deque

def main():

    inf = 1000000007
    n = int(input())
    e = [[] for _ in range(n)]
    d = [inf]*n

    for i in range(n):
        m = list(map(int,input().split()))
        for j in range(2,len(m)):
            e[m[0]-1].append(m[j]-1)

    d[0] = 0
    dq = deque([])
    dq.append([0,0])
    while dq:
        c,v = dq.popleft()
        for u in e[v]:
            if d[u]==inf:
                d[u] = c+1
                dq.append([c+1,u])

    for i in range(n):
        if d[i]==inf:print (i+1,-1)
        else        :print (i+1,d[i])

if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
INF = 1145141919810364364334
s = [None]
r = [None]

n = int(input())
for _ in range(n):
    temp = list(map(int,input().split()))
    s.append(temp[2:])
    
d = [INF] * (n+1)

d[1] = 0
q = deque()
q.append(1)

while q:
    x = q.popleft()
    for i in s[x]:
        if d[i] == INF:
            q.append(i)
            
        d[i] = min(d[x] + 1 , d[i])
        
for i in range(1,n+1):
    if d[i] == INF:
        d[i] = -1
    print(i,d[i])

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

from collections import deque
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  

n = ni()
g = []
for i in range(n):
    t = na()
    u = t[0] - 1
    k = t[1]
    v = [x-1 for x in t[2:]]
    g.append(v)
dist = [-1] * n
que = deque()
dist[0] = 0
que.append(0)
while que:
    
    v = que.popleft()
    for nv in g[v]:
        if dist[nv] != -1: continue
        dist[nv] = dist[v] + 1
        que.append(nv)

for i in range(n):
    print(i+1, dist[i])

Solution (Python):
import sys
from collections import deque
input = sys.stdin.readline
sys.setrecursionlimit(2 * 10**6)


def inpl():
    return list(map(int, input().split()))


N = int(input())

edge = {}
for _ in range(N):
    tmp = inpl()
    u, k = tmp[:2]
    edge[u] = tmp[2:]

d = {i: -1 for i in range(1, N + 1)}
d[1] = 0
Q = deque()
Q.append(1)
while Q:
    v = Q.popleft()
    for nv in edge[v]:
        if d[nv] != -1:
            continue
        d[nv] = d[v] + 1
        Q.append(nv)

for i in range(1, N + 1):
    print(i, d[i])

Solution (Python):

import sys
sys.setrecursionlimit(15000)
n = int(sys.stdin.readline())

ret = []
inp = sys.stdin.readlines()
G = [None]*(n+1)
depths = [-1]*(n+1)

for i in range(1,n+1):
  v = list(map(int,inp[i-1].split()))
  G[v[0]] = list(map(int,v[2:]))


nodes = [1]
depth = 0
while nodes:
  new = []
  for i in nodes:
    if depths[i] == -1:
      depths[i] = depth
      new += G[i]
    
  depth += 1
  nodes = new

for i in range(1,n+1):
  print(i,depths[i])

Solution (Python):
import queue


def bfs(g, s=1):
    global q

    dist = [-1] * len(g)
    dist[1] = 0
    q = queue.Queue()
    q.put(s)

    while not q.empty():
        v = q.get()
        if not G[v][1]:
            continue
        for vi in G[v][2:]:
            if dist[vi] >= 0:
                continue
            q.put(vi)
            dist[vi] = dist[v] + 1

    return dist


n = int(input())
G = [None]
for i in range(n):
    G.append(list(map(int, input().split())))

d = bfs(G)
for i in range(1, n + 1):
    print('%d %d' % (i, d[i]))

Solution (Python):


from collections import deque

n = int(input())

edges = [[] for _ in range(n)]
for _ in range(n):
    line = list(map(int, input().split()))
    u = line[0] - 1
    if len(line) != 2:
        v_list = line[1:]
        for v in v_list:
            edges[u].append(v - 1)


dist = [-1 for _ in range(n)]
que = deque()


def dfs(que, dist):
    while len(que) > 0:
        v = que.popleft()

        for v_adj in edges[v]:
            if dist[v_adj] == -1:
                dist[v_adj] = dist[v] + 1
                que.append(v_adj)


dist[0] = 0
que.appendleft(0)
dfs(que, dist)

for i in range(n):
    print(f"{i + 1} {dist[i]}")

Solution (Python):
n=int(input())
G=[]
for i in range(n):
    u,k,*l=map(int,input().split())
    G.append(l)



from collections import deque
def bfs(G,v,p):
    que=deque()
    que.append((v,p))
    log=[-1]*n
    log[0]=0
    while que:
        
        V,P=que.popleft()
        for next_v in G[V-1]:
            if log[next_v-1]!=-1:continue
            log[next_v-1]=log[V-1]+1
            que.append((next_v,V))
    return log

log=bfs(G,1,-1)
for i in enumerate(log,1):
    print(*i)

Solution (Python):
from collections import deque

n = int(input())
g = [list(map(int, input().split()))[2:] for _ in range(n)]
que = deque([0])
dist = [-1] * n
dist[0] = 0  
while que:  
    u = que.popleft()  
    for v in g[u]:
        v -= 1  
        if dist[v] == -1:  
            dist[v] = dist[u] + 1  
            que.append(v)  
for i in range(n):
    print(i + 1, dist[i])

Solution (Python):
ii = lambda : int(input())
li = lambda : list(map(int,input().split()))

from collections import deque

class tree:
    def __init__(self,n):
        self.n = n
        self.arr = [[] for i in range(self.n)]
        self.root = [-1]*n

    def add_arr(self, u, v):
        if v[0] != 0:
            self.arr[u-1] = v[1:]

n = ii()
t = tree(n)
for i in range(n):
    uk = li()
    t.add_arr(uk[0],uk[1:])
l = deque()
l.append(0)
t.root[0] = 0
while len(l)>0:
    p = l.popleft()
    for i in t.arr[p]:
        if t.root[i-1] == -1:
            t.root[i-1] = t.root[p]+1
            l.append(i-1)

for k,i in enumerate(t.root):
    print(k+1,i)

Solution (Python):
from collections import deque
n = int(input())
Ps = []
for _ in range(n):
  lis = list(map(int, input().split()))
  if len(lis)>2:
    Ps.append(lis[2:])
  else:
    Ps.append([])
ans = [-1]*n
ans[0] = 0
queue = deque()
checked = deque()
[queue.append([p, 1]) for p in Ps[0]]
checked.append(1)
while queue:
  t, pa = queue.popleft()
  if not t in checked:
    for i in Ps[t-1]:
      queue.append([i, t])
    ans[t-1] = ans[pa-1]+1
    checked.append(t)
for i, a in enumerate(ans):
  print(i+1, a)

Solution (Python):
n = int(input())
G = {}
D = [-1] * n
for _ in range(n):
    A = list(map(int, input().split()))
    G[A[0] - 1] = [a - 1 for a in A[2:]]



q = [(0, 0)]
while len(q) > 0:
    v, d = q[0]
    del q[0]
    if D[v] >= 0:
        continue
    D[v] = d

    for nv in G[v]:
        q.append((nv, d+1))

for i in range(n):
    print(i+1, D[i])

Solution (Python):
from collections import deque

def bfs():
	que=deque([])
	que.append(0)
	v[0]=0
	
	while que:
		p=que.popleft()
		for l in L[p]:
			if v[l-1]==-1:
				que.append(l-1)
				v[l-1]=v[p]+1
	
n=int(input())
L=[]
for i in range(n):
	A=[]
	A=list(map(int,input().split()))
	L.append(A[2:])
v=[-1]*n
bfs()
for i in range(n):
	print(i+1,v[i])

Solution (Python):
n = int(input())

A = [[] for i in range(n)]

for i in range(n):
  A[i] = list(map(int, input().split()))

f_inf = float("inf")
B = [[f_inf for i in range(2)] for j in range(n)]
B[0][1] = 0

for i in range(n):
  B[i][0] = i+1

def dbs(a):
  global order
  l = len(A[a-1])-2
  if l:
    for i in range(l):
      depth = B[a-1][1]+1
      b = A[a-1][i+2]
      if not b in order or depth < B[b-1][1]:
        B[b-1][1] = depth
        order.append(b)
        dbs(b)

order = [1]
dbs(1)

for i in range(n):
  if B[i][1] == f_inf:
    B[i][1] = -1
  print(" ".join(map(str, B[i])))

Solution (Python):
n=int(input())
dic=[[] for i in range(n)]
for i in range(n):
    a=list(map(int,input().split()))
    a=a[2:]
    dic[i]=list(map(lambda x:x-1,a))

from collections import deque
d=deque()
d.append(0) 
completed=[False]*n
distance=[999]*n
distance[0]=0
while d:
    now=d.popleft()
    completed[now]=True
    for x in dic[now]: 
        if completed[x]==False: 
            distance[x]=min(distance[now]+1,distance[x])  
            d.append(x)
for i in range(n):
    if distance[i]==999:
        distance[i]=-1
    print(i+1,distance[i])

Solution (Python):
from collections import deque
def bfs(g,v):
    q=deque([v]) ; vis=[0]*n
    vis[v]=1 ; stg[v]=0
    while q:
        v=q[0]
        for p in g[v]:
            if vis[p]==0: 
                q.append(p)
                vis[p]=1
                stg[p]=stg[v]+1
        q.popleft()
n=int(input())
g=[[] for i in range(n)]
for _ in range(n):
    a=[int(i)-1 for i in input().split()]
    for i in a[2:]: g[a[0]].append(i)
stg=[-1]*n
bfs(g,0)
for i in range(n):
    print(i+1,stg[i])

Solution (Python):
n = int(input())

adj_list = [[] for _ in range(n + 1)]

for i in range(n):
    tmp = list(map(int, input().split()))
    u = tmp[0]
    k = tmp[1]
    for v in range(2, 2 + k):
        adj_list[u].append(tmp[v])

d = [-1] * (n + 1)
q = []
q.append(1)
d[1] = 0

while len(q) > 0:
    u = q.pop(0)
    for v in adj_list[u]:
        if d[v] == -1:
            d[v] = d[u] + 1
            q.append(v)

for idx, d in enumerate(d):
    if idx != 0:
        print("%d %d" % (idx, d))

Solution (Python):
import queue

n = int(input())
v = [[]]
for _ in range(n):
    edges = sorted([int(x) for x in input().split()][2:])
    v.append(edges)
answers = [[idx, -1] for idx in range(n + 1)]
q = queue.Queue()
q.put(1)

answers[1][1] = 0
while not q.empty():
    node = q.get()
    for next_node in v[node]:
        if answers[next_node][1] != -1:
            continue
        q.put(next_node)
        answers[next_node][1] = answers[node][1] + 1

for idx, time in answers[1:]:
    print(idx, time)

Solution (Python):
import queue

N = int(input())
L = [list(map(int,input().split())) for _ in range(N)]
V = [(i+1) for i in range(N)]
E = []
for i in range(N):
    for j in range(len(L[i])-2):
        E.append((i+1,L[i][j+2]))

class Graph:
    def __init__(self,v,e):
        self.v = v
        self.e = e
        self.v_visited = [False for _ in range(N)]
    def visited(self,v):
        self.v_visited[v-1] = True

q = queue.Queue()
g = Graph(V,E)
TS = [-1 for _ in range(N)]

def bfs(u):
    q.put(u)
    g.visited(u)
    TS[u-1] = 0
    while not q.empty():
        u = q.get()
        for v in g.v:
            if (u,v) in g.e and g.v_visited[v-1] == False:
                q.put(v)
                g.visited(v)
                TS[v-1] = TS[u-1]+1
bfs(1)

for i in range(N):
    print(i+1,TS[i])

Solution (Python):
n = int(input())
E = [[]]*n

for i in range(n):
    inputs = list(map(int, input().split()))
    if inputs[1]>0:
        for e in inputs[2:]:
            E[i] = E[i] + [e-1]

visited = [-1]*n
dist = [-1]*n
dist[0] = 0

from collections import deque

d = deque()
d.append(0)
visited[0] = 1

while len(d):
    nd = d.popleft()
    
    for e in E[nd]:
        
        if visited[e]<0:
            d.append(e)
            dist[e] = dist[nd] + 1
            visited[e] = 1
    
            

for i in range(n):
    print(i+1, dist[i])

Solution (Python):
n = int(input())

graphs = []

for _ in range(n):
    graphs.append(list(map(int, input().split()))[2:])


def bfs(graphs, seen_points, score, scores, queue):
    while len(queue) > 0:
        start_point = queue.pop(0)
        if seen_points[start_point - 1] == 2:
            continue
        else:
            next_points = [
                point for point in graphs[start_point - 1] if seen_points[point - 1] == 0]
            if len(next_points) >= 1:
                score += 1
                for point in next_points:
                    queue.append(point)
                    if seen_points[point - 1] == 0:
                        seen_points[point - 1] = 1
                        scores[point - 1] = scores[start_point - 1] + 1
                seen_points[start_point - 1] = 2


seen_points = [0 for _ in range(n)]
scores = [-1 for _ in range(n)]
scores[0] = 0
queue = [1]
bfs(graphs, seen_points, 0, scores, queue)

for index, score in enumerate(scores):
    print(index + 1, score)

Solution (Python):
N = int(input())
G = [None for i in range(N)]
for i in range(N):
    u, k, *vs = map(int, input().split())
    G[u-1] = [e-1 for e in vs]


from collections import deque
dist = [-1]*N
que = deque([0])
dist[0] = 0
while que:
    v = que.popleft()
    d = dist[v]
    for w in G[v]:
        if dist[w] > -1:
            continue
        dist[w] = d + 1
        que.append(w)

for i in range(N):
    print(i+1, dist[i])

Solution (Python):
import sys
import math
import string
import fractions
import random
from operator import itemgetter
import itertools
from collections import deque
import copy
import heapq
import bisect

MOD = 10 ** 9 + 7
INF = float('inf')
input = lambda: sys.stdin.readline().strip()

sys.setrecursionlimit(10 ** 8)

n = int(input())
dis = [-1] * n
info = [list(map(int, input().split())) for _ in range(n)]

stack = [[0, 0]]
ans = 0
while len(stack) > 0:
    num = stack.pop(0)
    if dis[num[0]] == -1:
        dis[num[0]] = num[1]
    for i in info[num[0]][2:]:
        if dis[i-1] == -1:
            stack.append([i - 1, num[1] + 1])
for i in range(n):
    print(str(i+1) + " " + str(dis[i]))

Solution (Python):
import sys

from collections import deque

def fillMatrix():
    for i in range(n):
        u, k, *v = map(int, input().split())
        for j in v:
            matrix[i][j-1] = 1

def bfs(s):
    status[s] = VISITING
    distance[s] = 0
    Q.append(s)
    while len(Q) > 0:
        u = Q.popleft()
        for v in range(n):
            if matrix[u][v] and status[v] == NOT_VISITED:
                status[v] = VISITING
                distance[v] = distance[u] + 1
                Q.append(v)
        status[u] = VISITED

n = int(input())
matrix = [[0]*n for i in range(n)]
INFTY = 1 << 21
distance = [INFTY] * n

NOT_VISITED = 0 
VISITING = 1 
VISITED = 2 
status = [NOT_VISITED] * n
Q = deque()

fillMatrix()
bfs(0)

for i in range(n):
    ans = []
    ans.append(i+1)
    if distance[i] == INFTY:
        distance[i] = -1
    ans.append(distance[i])
    ans = map(str, ans)
    print(' '.join(ans))

Solution (Python):
import sys
from collections import deque

sys.setrecursionlimit(50000)

n = int(input())

data = [[] for _ in range(n)]
answer = [-1]*n
answer[0] = 0
for i in range(n):
    line = list(map(int, input().split(" ")))
    if line[1] != 0:
        for e in line[2:]:
            data[i].append(e)


def bfs(vs, count=0):
    next_vs = []
    for v in vs:
        for n_v in data[v-1]:
            if answer[n_v-1] == -1:
                answer[n_v-1] = count+1
                next_vs.append(n_v)
    if not next_vs == []:
        bfs(next_vs, count+1)


bfs([1])

for i in range(n):
    line = str(i+1) + " " + str(answer[i])
    print(line)

Solution (Python):



import queue

N=int(input())
Graph=[[] for _ in range(N+1)]
dist=[-1 for _ in range(N+1)]
for i in range(1,N+1):
    Graph[i]=list(map(int,input().split()))[2:]


que=queue.Queue()
que.put(1)
dist[1]=0
while not que.empty():
    v=que.get()
    for nv in Graph[v]:
        if dist[nv] != -1:
            continue
        dist[nv]=dist[v]+1
        que.put(nv)
for i in range(1,N+1):
    print(i,dist[i],sep=" ")

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n = I()
    v = []
    for i in range(n):
        e = LI()
        u = e[2:]
        for i in range(len(u)):
            u[i] -= 1
        v.append(u)
    d = [-1]*n
    d[0] = 0
    q = deque([0])
    while q:
        x = q.popleft()
        nd = d[x]+1
        for y in v[x]:
            if d[y] < 0:
                d[y] = nd
                q.append(y)
    for i in range(n):
        print(i+1,d[i])
    return


if __name__ == "__main__":
    solve()

Solution (Python):
n = int(input())
g = [input().split()[2:] for _ in range(n)]

from collections import deque
que = deque()
que.append(0)
d = [0] + [-1] * n

while que:
    u = que.popleft()

    for v in g[u]:
        v = int(v) - 1

        if d[v] < 0:
            d[v] = d[u] + 1
            que.append(v)

for i in range(n):
    print(i+1, d[i])

"""
・グラフの数を受け取る
・グラフを作る．今回は隣接リストで必要な部分だけを残してリスト化する
・キュー用の配列を作る（これはなんでもいい．普通のリストでも可）．そのキューには1番初めのスタート位置を入れておく
・最短距離を置いておくリストを用意
・queの中身がなくなるまで続ける
・queの中身を取り出して，それにくっついてるノードを全て舐めていく．int方で入力を受け取っていないから注意．1-indexを0-indexに変える．
・もしそこにまだBFSが訪れていなかったら，そこに前回の場所から1足した物を代入
・探索用のqueに追加しておく．追加しておくことでまたそのノードとつながってるところを調べることができる
・最後は出力．全てのノードの最短距離を出力
"""

Solution (Python):
if __name__ == '__main__':
    from sys import stdin
    input = stdin.readline

    from collections import deque, defaultdict
    from copy import deepcopy

    INFTY = -1   

    n = int(input())

    M = [[0]*n for _ in range(n)]

    def bfs(s):
        q = deque()
        q.append(s)
        d = [INFTY]*n
        d[s] = 0
        while q: 
            u = q.popleft()  
            for v in range(n):
                if M[u][v] == 0:
                    continue
                if d[v] != INFTY:
                    continue
                d[v] = d[u] + 1
                q.append(v)
        for i in range(n):
            print(str(i+1) + ' ' + str(d[i]))

    for _ in range(n):
        u, k, *vv = map(int, input().split())
        u -= 1
        for v in vv:
            v -= 1
            M[u][v] = 1

    bfs(0)

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline


N = int(input())
G = [[] for _ in range(N)]
for _ in range(N):
    ls = list(map(int, input().split()))
    u = ls[0] - 1
    for v in ls[2:]:
        G[u].append(v - 1)

dist = [-1] * N
que = deque([0])
dist[0] = 0

while que:
    v = que.popleft()
    d = dist[v]
    for w in G[v]:
        if dist[w] > -1:
            continue
        dist[w] = d + 1
        que.append(w)

for v in range(N):
    print("{} {}".format(v + 1, dist[v]))

Solution (Python):
from collections import deque

n = int(input())
g = [None] * n
visited = [0] * n
dist = [-1] * n
Q = deque()

while n:
    l = list(map(int, input().split()))
    g[l[0]-1] = [i-1 for i in l[2:]]
    n -= 1

Q.append((0, 0)) 
visited[0] = 1

while Q:
    i, d = Q.popleft()         
    dist[i] = d
    for c in g[i]:
        if not visited[c]:
            visited[c] = 1
            Q.append((c, d+1))

for i, d in enumerate(dist):
    print(i+1, d)

Solution (Python):
n = int(input())
d = [-1]*(n+1)
adjacent_list = [[] for _ in range(n+1)]
for _ in range(n):
    edge = list(map(int,input().split()))
    if len(edge) >= 3:
        adjacent_list[edge[0]].extend(edge[2:])

from collections import deque

que = deque()
que.append(1)
d[1] = 0
while len(que) != 0:
    v = que.popleft()
    for nv in adjacent_list[v]:
        if d[nv] == -1:
            d[nv] = d[v] + 1
        else:
            continue
        que.append(nv)

for i,dist in enumerate(d):
    if i == 0:
        continue
    print(i,dist)

Solution (Python):
n = int(input())
v = []
for i in range(n):
    v_i = list(map(int,input().split()))[2:]
    v.append(v_i)
    
d = [-1]*n
d[0]=0
queue = [1]
dis = 1
while len(queue)!=0:
    queue2 = []
    for i in queue:
        for nex in v[i-1]:
            if d[nex-1]==-1:
                d[nex-1]=dis
                queue2.append(nex)
    dis +=1
    queue = queue2

for i in range(n):
    print(i+1,d[i])

Solution (Python):
import sys
import queue
input = sys.stdin.readline
n = int(input())
g = [[] for _ in range(n+1)]
d = [-1 for _ in range(n+1)]
for _ in range(n):
    c = list(map(int,input().split()))
    g[c[0]] = c[2:]

depth = 0
q = queue.Queue()
p = queue.Queue()
q.put(1)
while not q.empty():
    while not q.empty():
        s = q.get()
        if d[s] < 0:
            d[s] = depth
            for i in g[s]:
                p.put(i)
    p, q = q, p
    depth += 1

for i in range(1,n+1):
    print (i,d[i])

Solution (Python):
import queue

n = int(input())
graph = {}
for _ in range(n):
  i = list(map(int,input().split()))
  graph[i[0]] = i[2:]

dist = [-1 for i in range(n)]
todo = queue.Queue()
seen = set()

dist[0] = 0
todo.put(1)

while (not todo.empty()):
  now = todo.get()
  for nx in graph[now]:
    if (dist[nx-1] != -1):
      continue
    dist[nx-1] = dist[now-1] + 1
    todo.put(nx)

for i in range(n):
  print(i+1, dist[i])

Solution (Python):
from collections import deque

def main():
    n = int(input())
    V = [None]*(n+1)
    ans = [None]*(n+1)
    for i in range(1, n+1):
        _, _, *v = map(int, input().split())
        V[i] = v
    q = deque([1])
    ans[1] = 0
    while q:
        node = q.pop()
        d = ans[node]+1
        for v in V[node]:
            if ans[v] is None:
                ans[v] = d
                q.appendleft(v)
    print(1, 0)
    for i, distance in enumerate(ans[2:], 2):
        print(i, distance or -1)

if __name__ == "__main__":
    main()

Solution (Python):
import sys
from collections import deque

n = int(sys.stdin.readline().strip())
edges = [[] for _ in range(n)]
for _ in range(n):
    tmp = list(map(int, sys.stdin.readline().strip().split(" ")))
    for node in tmp[2:]:
        edges[tmp[0] - 1].append(node-1)


distance = [0] * n
q = deque()
q.append((0, 0))
visited = set()
while q:
    node, d = q.popleft()
    
    if node in visited:
        continue
    distance[node] = d
    visited.add(node)
    for next in edges[node]:
        
        q.append((next, d + 1))

for i, d in enumerate(distance):
    if i == 0:
        print(1, 0)
    else:
        print(i + 1, d if d > 0 else -1)

Solution (Python):
import collections
n = int(input())
adj_list = []

for _ in range(n):
    adj = list(map(int, input().split(" ")))
    adj_list.append([c - 1 for c in adj[2:]])

distances = [-1 for _ in range(n)]
queue = collections.deque()
queue.append(0)
distances[0] = 0

while queue:
    p = queue.popleft()

    for next_p in adj_list[p]:
        if distances[next_p] == -1:
            distances[next_p] = distances[p] + 1
            queue.append(next_p)

for i in range(n):
    print(i+1, distances[i])

Solution (Python):
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YNL = {False: 'No', True: 'Yes'}
YNU = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False



def bfs(graph, initial):
    n = len(graph) - 1
    dist = [-1] * (n + 1)
    q = deque([initial])
    visited = [False] * (n + 1)
    visited[initial] = True
    dist[initial] = 0

    while len(q) != 0:
        edge = q.popleft()
        nxt = graph[edge]

        for i, e in enumerate(nxt):
            if visited[e] is False:
                q.append(e)
                dist[e] = dist[edge] + 1
                visited[e] = True

    return dist


def main():
    N = I()
    graph = [[] for i in range(N+1)]

    for i in range(N):
        a = LI()
        edge = a[0]
        if a[1] == 0:
            continue
        for e in a[2:]:
            graph[edge].append(e)
            

    
    ret = bfs(graph, 1)
    for i in range(1, N+1):
        print(i, ret[i])


if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
E = [[] for _ in range(N+1)]
for _ in range(N):
	tmp = list(map(int, input().split()))
	if tmp[1] == 0:
		continue
	E[tmp[0]] = tmp[2:]

cnt = [0 for _ in range(N+1)]
q = [1]

while q:
	cp = q.pop(0)
	for np in E[cp]:
		if cnt[np] != 0:
			continue
		
		cnt[np] = cnt[cp] + 1
		q.append(np)

for ind, cost in enumerate(cnt):
	if ind == 0:
		continue
	if ind == 1:
		print(ind, 0)
	else:
		if cost == 0:
			print(ind, -1)
		else:
			print(ind, cost)

Solution (Python):
from collections import deque

N = int(input())
nodes = []
G ={}
is_visited = {}
q = deque()

for _ in range(N):
    lst = list(map(int, input().split()))
    idx = lst[0]
    nodes.append(idx)
    is_visited[idx] = False
    degree = lst[1]
    if degree > 0:
        G[idx] = lst[2:]
    else:
        G[idx] = []

INF = 10**12
costs = [INF]*N


que = deque()  
que.append(1)
costs[0] = 0
while que:
    node_id = que.popleft()  
    cost = costs[node_id-1]
    for next_id in G[node_id]:
        if (costs[next_id-1] == INF):
            que.append(next_id)
            costs[next_id-1] = cost + 1
        
for i in range(N):
    if costs[i] != INF:
        print(i+1, costs[i])
    else:
        print(i+1, -1)

Solution (Python):


import sys

from queue import Queue


class BFS():
    INFTY = sys.maxsize

    def __init__(self, M, n, debug=False):
        self.M = M
        self.n = n
        
        self.d = [self.INFTY] * n
        self.debug = debug

    def bfs(self, s):
        q = Queue()
        q.put(s)
        self.d[s] = 0
        self.debug_print(q)

        while not q.empty():
            u = q.get()
            for v in range(self.n):
                if self.M[u][v] == 0:
                    continue
                if self.d[v] != self.INFTY:
                    continue
                self.d[v] = self.d[u] + 1
                q.put(v)
                self.debug_print(q)

        for i in range(self.n):
            if self.d[i] == self.INFTY:
                d = -1
            else:
                d = self.d[i]
            print(f'{i+1} {d}')

    def debug_print(self, q):
        if not self.debug:
            return
        print('d: ', self.d)
        print('q: ', q.queue)
        print('-------------------------')


def main():
    n = int(input())
    M = [[0] * n for _ in range(n)]

    for i in range(n):
        line = input()
        inputs = [int(x) for x in line.split(' ')]
        u = inputs.pop(0)
        u -= 1                  
        _ = inputs.pop(0)       
        for v in inputs:
            v -= 1              
            M[u][v] = 1

    BFS(M, n).bfs(0)


if __name__ == '__main__':
    main()

Solution (Python):

'''
所要時間は、分位であった。
'''




import sys


from collections import deque


def main():
    inf = 10000
    n = int(input())
    D = [inf for i in range(n)]
    L = [[] for i in range(n)]
    for i, line in enumerate(sys.stdin):
        L[i] = list(map(lambda x: int(x)-1, list(line.strip("\n").split())))

    q = deque([0])
    D[0] = 0
    while(len(q)):
        u = q.popleft()
        if L[u][1] == -1:
            continue
        for j in range(2,len(L[u])):
            if D[L[u][j]] == inf:
                q.append(L[u][j])
            D[L[u][j]] = min(D[L[u][0]] + 1, D[L[u][j]]) 

                      
    for i in range(n):
        print("{} {}".format(i+1,D[i])) if D[i] < inf else print("{} {}".format(i+1,-1))
            
if __name__ == '__main__':
    main()

Solution (Python):
class Myqueue():

    def __init__(self, size):
        self.size = size
        self.N = [None for _ in range(size)]
        self.head = 0
        self.tail = 0

    def is_empty(self):
        return self.head == self.tail

    def is_full(self):
        return self.head == (self.tail + 1) % self.size

    def enqueue(self, x):
        if self.is_full():
            raise OverflowError
        self.N[self.tail] = x
        self.tail += 1
        if self.tail == self.size:
            self.tail = 0

    def dequeue(self):
        if self.is_empty():
            raise IndexError
        x = self.N[self.head]
        self.head += 1
        if self.head == self.size:
            self.head = 0
        return x


class Node:

    def __init__(self):
        self.distance = -1
        self.status = 0

    def input_data(self, nodes):
        data = input().split()
        self.number = int(data[0])
        self.v = [nodes[int(x) - 1] for x in data[2:]]

n = int(input())
queue = Myqueue(n)
nodes = [Node() for _ in range(n)]
[node.input_data(nodes) for node in nodes]
nodes[0].status = 1
nodes[0].distance = 0
queue.enqueue(nodes[0])
while not queue.is_empty():
    u = queue.dequeue()
    for v in u.v: 
        if v.status == 0:
            v.status = 1
            v.distance = u.distance + 1
            queue.enqueue(v)
    u.status = 2


nodes.sort(key=lambda i: i.number)
for node in nodes:
    print(f"{node.number} {node.distance}")

Solution (Python):
from collections import deque


l = int(input())
rlist = []
for i in range(l):
    li = list(map(int, input().split()))
    rlist.append(deque([ll-1 for ll in li[2:]]))


color = ['white'] * l
queue = deque([])
d = [10000000] * l

def bfs(u):
    color[u] = 'gray'
    d[u] = 0
    queue.append(u)

    while(len(queue) > 0):
        u = queue.popleft()
        for rl in rlist[u]:
            if color[rl] == 'white':
                color[rl] = 'gray'
                d[rl] = d[u] + 1
                queue.append(rl)
        color[u] = 'black'

bfs(0)

for i in range(l):
    if d[i] == 10000000:
        d[i] = -1

for i in range(l):
    print(str(i+1) + ' ' + str(d[i]))

Solution (Python):
from collections import deque


def breadth_first_search(adj_matrix, n):
    distance = [0] + [-1] * (n - 1)
    searching = deque([0])
    while len(searching) > 0:
        start = searching.popleft()
        for end in range(n):
            if adj_matrix[start][end] and distance[end] == -1:
                searching.append(end)
                distance[end] = distance[start] + 1
    return distance


def main():
    n = int(input())
    adj = [[False for _ in range(n)] for _ in range(n)]
    for _ in range(n):
        ukv = input().split()
        id = int(ukv[0])
        dim = int(ukv[1])
        if dim > 0:
            nodes = map(int, ukv[2:])
            for node in nodes:
                adj[id - 1][node - 1] = True
    distance = breadth_first_search(adj, n)
    for i in range(n):
        print("{} {}".format(i + 1, distance[i]))


if __name__ == "__main__":
    main()