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):
import sys
from collections import deque

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n = int(input())
    edge = [[] for _ in range(n)]
    for _ in range(n):
        u, k, *V = map(int, input().split())
        for v in V:
            edge[u - 1].append(v - 1)

    depth = [f_inf] * n
    depth[0] = 0
    que = deque([0])
    while que:
        v = que.popleft()
        for u in edge[v]:
            if depth[u] == f_inf:
                depth[u] = depth[v] + 1
                que.append(u)

    for i in range(n):
        print(i + 1, depth[i] if depth[i] != f_inf else -1)


if __name__ == '__main__':
    resolve()

Solution (Python):
from collections import deque
from collections import defaultdict

n = int(input())

graph = defaultdict(list)

for i in range(n):
    u, k, *v = map(int, input().split())
    for v in v:
        graph[u].append(v)

ans = [-1] * (n + 1)

q = deque([1])
ans[1] = 0

while q:
    c = q.popleft()
    for v in graph[c]:
        if ans[v] == -1:
            ans[v] = ans[c] + 1
            q.append(v)

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

Solution (Python):
from collections import deque
n=int(input())
l=[0]+[list(map(int,input().split()))[2:] for _ in range(n)]

flg=["white"]*(n+1)
dist=[-1]*(n+1)

def BFS(x):

    queue = deque([x])
    dist[x]=0
    flg[x]="gray"

    while queue:
        current=queue.popleft()
        for i in l[current]:
            if flg[i]=="white":
                queue.append(i)
                flg[i]="gray"
                dist[i]=dist[current]+1
        flg[current]="black"

BFS(1)

for num,i in enumerate(dist[1:],1):
    print(num,i)

Solution (Python):
from collections import deque
n = int(input())
adj = [ [] for _ in range(n+1) ]
for _ in range(n):
  lst = list(map(int,input().split()))
  if lst[1] > 0:
    adj[lst[0]] = lst[2:]

q = deque([1])
dist = [-1] * (n+1)
dist[1] = 0

q = deque([1])
while q:
  node = q.popleft()

  for nei in adj[node]:
    if dist[nei] != -1: continue
    dist[nei] = dist[node] + 1
    q.append(nei)

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

Solution (Python):
from collections import deque
n=int(input())
v=[[] for _ in range(n)]
dist=[n+1]*n
dist[0]=0
for i in range(n):
    l=list(map(int,input().split()))
    if l[1]==0:
        continue
    else:
        for j in l[2:]:
            v[l[0]-1].append(j-1)

flg=1
q=deque()
while flg==1:
    flg=0
    q=deque()
    for i in range(n):
        q.append(i)
        chk=[0]*n
        while q:
            x=q.popleft()
            chk[x]=1
            d=dist[x]
            for j in v[x]:
                if chk[j]==1:
                    continue
                else:
                    if dist[j]>d+1:
                        flg=1
                        dist[j]=d+1
                        q.append(j)

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

Solution (Python):
from collections import deque
n = int(input())
u = []
k = []
v = []

for i in range(n):
    tmp = list(map(int, input().split()))
    u.append(tmp[0])
    k.append(tmp[1])
    if tmp[1] != 0:
        v.append(tmp[2:])
    else:
        v.append([])
        
d = deque([1])
dis = [-1]*n
dis[0] = 0
visit = [False]*n
visit[0] = True
while len(d) > 0:
    go = d[0]
    flag = False
    for i in v[go-1]:
        if not visit[i-1]:
            d.append(i)
            dis[i-1] = dis[go-1] + 1
            visit[i-1] = True
            flag = True
    d.popleft()
    
for i in range(n):
    print(i+1, dis[i])

Solution (Python):
from collections import deque
N=int(input())
color=["white"]*(N+1)
rinsetu=[[] for i in range(N+1)]
for i in range(N):
    a,*b=list(map(int,input().split()))
    for idx,j in enumerate(b):
        if idx==0:continue
        rinsetu[a].append(j)
distance=[10**5]*(N+1)
distance[1]=0
def bfs():
    d = deque()
    d.append(1)
    while(d):
        num=d.popleft()
        color[num] = "black"
        for i in rinsetu[num]:
            if color[i]=="white":
                d.append(i)
                distance[i]=min(distance[num]+1,distance[i])

bfs()
for i in range(1,N+1):
    if distance[i]==10**5:distance[i]=-1
    print(i,distance[i])

Solution (Python):
import queue
from collections import namedtuple
T = namedtuple("T", "u d")

n = int(input())
path = dict()
ans = [-1] * (n + 1)

for i in range(n):
    a = [int(x) for x in input().split()]
    a.reverse()

    u, k = a.pop(), a.pop()
    path[u] = set()
    for j in range(k):
        path[u].add(a.pop())


def bfs(s):
    q = queue.Queue()
    q.put(s)

    while q.qsize() != 0:
        p = q.get()
        if p.d < ans[p.u] or ans[p.u] < 0:
            ans[p.u] = p.d
            for r in path[p.u]:
                q.put(T(r, p.d + 1))


bfs(T(1, 0))
for i in range(1, n + 1):
    print(i, ans[i])

Solution (Python):
from collections import deque
n = int(input())
grap = [[]]
for i in range(n):
    u,k,*v = map(int,input().split())
    grap.append(v)

dis = [-1]*(n+1)
dis[0] = 0
dis[1] = 0

d = deque()
d.append(1)
while d:
    v = d.popleft()
    for i in grap[v]:
        if dis[i] != -1:
            continue
        dis[i] = dis[v] + 1
        d.append(i)

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

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

tree = [[] for _ in range(N)]

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

ans = [float('inf') for _ in range(N)]
ans[0] = 0

from collections import deque

q = deque([(0, 0)])

while q:
    p, d = q.popleft()
    for c in tree[p]:
        if ans[c-1] > d+1:
            ans[c-1] = d+1
            q.append((c-1, d+1))

for i in range(N):
    if ans[i] == float('inf'):
        print(i+1, -1)
    else:
        print(i+1, ans[i])

Solution (Python):
import sys
import itertools

import time
import math
import heapq
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines




n = int(input())

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

for i in range(n):
    line = list(map(int, input().split()))
    u = line[0]
    for j in range(line[1]):
        v = line[2 + j]
        adj[u - 1].append(v - 1)



import queue
q = queue.Queue()
visited = [False] * n
dist = [-1] * n

visited[0] = True
dist[0] = 0
q.put(0)
while not q.empty():
    v = q.get()
    for u in adj[v]:
        if visited[u]:
            continue
        visited[u] = True
        dist[u] = dist[v] + 1
        q.put(u)

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

Solution (Python):
import collections

N = int(input())
route = []
for i in range(N):
    a = list(map(int, input().split()))
    route.append(a[2:])
ans = [-1 for _ in range(N)]
ans[0] = 0
check = collections.deque([0])
while check:
    now = check.popleft()
    for next in route[now]:
        next -= 1
        if ans[next] == -1:
            check.append(next)
            ans[next] = ans[now]+1
for i in range(N):
    print(i+1, ans[i])

Solution (Python):
import collections
n= int(input())
g=[]
for _ in range(n):
    v,k,*varray= map(int,input().split())
    g.append(varray)
        

d= [-1]* (n+10)
d[0]=0
q= collections.deque()
q.append(0)
while len(q)>  0:
    cur = q.popleft()
    for next in g[cur]:
        if d[next-1]== -1:
            d[next-1]= d[cur]+1
            q.append(next-1)
            
for i in range(n):
    print(i+1,d[i])

Solution (Python):
import collections

N = int(input())
M = []
for i in range(N):
    a = list(map(int,input().strip().split()))
    b = [int(i+1 in a[2:]) for i in range(N)]
    M.append(b)

D = [-1 for _ in range(N)]
D[0] = 0 
Q = collections.deque()
Q.append(0) 
while len(Q) > 0:
    
    cur = Q.popleft()
    for dst in range(N):
        
        if M[cur][dst] == 1 and D[dst] == -1:
            D[dst] = D[cur]+1
            Q.append(dst) 
for v in range(N):
    print(v+1, D[v])

Solution (Python):
from collections import deque
n=int(input())
d=[-1]*(n+1)
d[1]=0
v=[[] for i in range(n+1)]
for i in range(n):
  a=list(map(int,input().split()))
  v[a[0]]=a[2:]
q=deque()
q.append(1)
while len(q)>0:
  curr=q.popleft()
  for i in v[curr]:
    if d[i]==-1:
      d[i]=d[curr]+1
      q.append(i)
for i in range(1,n+1):
  print(f'{i} {d[i]}')

Solution (Python):
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

from collections import deque,defaultdict,Counter
def main():
    N = int(input())
    G = [[] for _ in range(N)]
    for i in range(N):
        A = list(map(int,input().split()))
        for a in A[2:]:
            a -= 1
            G[i].append(a)
    
    q = deque([0])
    dist = [-1] * N
    dist[0] = 0
    while q:
        v = q.popleft()
        for e in G[v]:
            if dist[e] >= 0:
                continue
            dist[e] = dist[v] + 1
            q.append(e)
    
    ans = [(i + 1,dist[i]) for i in range(N)]
    for t in ans:
        print(*t)
if __name__ == '__main__':
    main()

Solution (Python):
import collections

N = int(input())
UKV = [list(map(int,input().split())) for _ in range(N)]

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

G = [[]]*N
for ukv in UKV:
    G[ukv[0]-1] = sorted(ukv[2:])

dist[0] = 0
que.append(1)

while len(que) != 0:
    v = que.popleft()
    for nv in G[v-1]:
        if dist[nv-1] != -1:
            continue
        dist[nv-1] = dist[v-1] + 1
        que.append(nv)

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

Solution (Python):



from collections import deque

n = int(input())
u_l = []
k_l = []
v_l = []

for i in range(n):
    _v_l = []
    for j, _ in enumerate(input().split()):
        if j == 0:
            u_l.append(int(_))
        elif j == 1:
            k_l.append(int(_))
        else:
            _v_l.append(int(_))
    v_l.append(_v_l)
        
d_l = [-1]*n
d_l[0] = 0
s_dq = deque([1])
while len(s_dq) > 0:
    _s = s_dq.popleft()
    _s -= 1
    for i in range(k_l[_s]):
        _v = v_l[_s][i]
        if d_l[_v-1] == -1:
            s_dq.append(_v)
            d_l[_v-1] = d_l[_s] + 1

for _id, _d in zip(range(1,n+1), d_l):
    print(_id, _d)

Solution (Python):
from collections import deque

N = int(input())

edge = [[] for _ in range(N)]
for _ in range(N):
    t = list(map(int,input().split()))
    if t[1] != 0:
        edge[t[0]-1] = list(map(lambda x:int(x)-1, t[2:]))

dist = [-1]*N
dist[0] = 0
        
q = deque([0])
while q:
    now = q.popleft()
    for nxt in edge[now]:
        if dist[nxt] == -1:
            dist[nxt] = dist[now] + 1
            q.append(nxt)
        else:
            dist[nxt] = min(dist[nxt], dist[now] + 1)

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

Solution (Python):
from collections import deque

def bfs(maze, visited, x):
    queue = deque([x])
    visited[x] = 1
    ans_list[x] = 0
    while queue:
      
        y = queue.popleft()
        r = maze[y - 1][2:]
        for i in r:
            if visited[i] == 0:
              if ans_list[i] >= 10 ** 10:
                ans_list[i] = ans_list[y] + 1
                queue.append(i)
    return 0
              

                
if __name__ == "__main__":
  N = int(input())
  A = [0] * N
  for i in range(N):
    A[i] = list(map(int, input().split()))
  visited = [0] * (N + 1)
  ans_list = [float("inf")] * (N + 1)
  bfs(A, visited, 1)
  
  for i in range(1, N + 1):
    if ans_list[i] >= 10 ** 10:
      print(i, -1)
    else:
      print(i, ans_list[i])

Solution (Python):
from collections import deque

n = int(input())
graph_W = []
for _ in range(n):
    graph_W.append(list(map(int, input().split())))
    
num_root = [0]*n
work_queue = deque([])
visited = set()

work_queue.append(1)
visited.add(1)
cnt = 0
while work_queue:
    here = work_queue.popleft() - 1
    num_node = graph_W[here][1]
    cnt += 1
    if num_node == 0:
        continue
    for k in range(num_node):
        num_graph = graph_W[here][k+2]
        if num_graph not in visited:
            work_queue.append(num_graph)
            visited.add(num_graph)
            num_root[num_graph-1] = num_root[here] + 1


print(1,0)
for i in range(1,n):
    if num_root[i] != 0:
        print(i+1,num_root[i])
    else:
        print(i+1,-1)

Solution (Python):
from collections import deque

n = int(input())
graph = []

for _ in range(n):
    u = list(map(int, input().split()))

    if u[1] == 0:
        graph.append([])
    else:
        graph.append(list(map(lambda x: x - 1, u[2: u[1] + 2])))

dist = [-1] * n


def bfs(x):
    q = deque([])
    dist[x] = 0
    q.append(x)

    while q:
        x = q.popleft()

        for nx in graph[x]:
            if dist[nx] != -1:
                continue
            else:
                dist[nx] = dist[x] + 1
                q.append(nx)


bfs(0)

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

Solution (Python):
n = int(input())
G = [[] for i in range(n)] 
for i in range(n):
    a = [int(i) for i in input().split()]
    G[a[0]-1] = [i-1 for i in a[2:]]

d = [-1] * n
todo = [0]
d[0] = 0

while(todo != []):
    v = todo.pop(0)
    for i in G[v]:
        if d[i] == -1:
            d[i] = d[v]+1
            todo.append(i)

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

Solution (Python):
def main():
    import sys
    N = int(sys.stdin.readline())
    L1 = [list(map(int, sys.stdin.readline().split())) for i in range(N)]
    L = [[] for _ in range(N+1)]
    for row in L1:
        L[row[0]] += row[2:]
    
    
    d = [-1 for i in range(N+1)] 
    def bfs(p, queue=[]):
        queue+=[p]
        d[p]=0
        while queue:
            now = queue.pop(0)
            for ch in L[now]:
                if d[ch] ==-1: 
                    d[ch] = d[now]+1
                    queue +=[ch]
    
    
    bfs(1)
    for idx, ans in enumerate(d[1:]):
        print(idx+1, ans)


if __name__=='__main__':
    main()

Solution (Python):
import queue

n = int(input())
graph = []
for _ in range(n):
    line = list(map(int, input().split()))
    graph.append([v - 1 for v in line[2:]])

q = queue.Queue()
q.put(0)
dist = [-1] * n
dist[0] = 0

while True:
    v = q.get()
    for next_v in graph[v]:
        if dist[next_v] == -1: 
            q.put(next_v)
            dist[next_v] = dist[v] + 1

    if q.empty():
        break

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

Solution (Python):

n = int(input())
X = []
for _ in range(n):
    x = list(map(int, input().split()))
    if x[1] == 0:
        X.append([])
    else:
        X.append(x[2:])
Y = [-1 for _ in range(n)]
def search(i = 0, d = 0):
    if Y[i] > d or Y[i] < 0:
        Y[i] = d
        for x in X[i]:
            search(x - 1, d + 1)
    
search()

for i, y in enumerate(Y):
    print('{} {}'.format(i + 1, y))

Solution (Python):
import math
import string
import collections
from collections import Counter
from collections import deque
from decimal import Decimal
import sys
import fractions


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


def nCr(n, r):
    return math.factorial(n)//(math.factorial(n-r)*math.factorial(r))


def has_duplicates2(seq):
    seen = []
    for item in seq:
        if not(item in seen):
            seen.append(item)
    return len(seq) != len(seen)


def divisor(n):
    divisor = []
    for i in range(1, n+1):
        if n % i == 0:
            divisor.append(i)
    return divisor



dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]
n = int(input())
g = [None]*n
for i in range(n):
    g[i] = readints()

G = [None]*n
for i in range(n):
    G[i] = []

for i in range(n):
    if len(g[i]) >= 3:
        for j in range(2, len(g[i])):
            
            G[i].append(g[i][j])

dist = [-1]*n
dist[0] = 0
d = deque()
d.append(0)

while(len(d) != 0):
    v = d.popleft()
    if G[v] != []:
        for nv in G[v]:
            if dist[nv-1] != -1:
                continue
            dist[nv-1] = dist[v]+1
            d.append(nv-1)
for i in range(n):
    print(i+1, dist[i])

Solution (Python):
import sys

n = int(input())
G = [None]*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):
from collections import deque
n = int(input())
G = []
for _ in range(n):
    u, k, *v = map(int, input().split())
    u -= 1
    G.append(v)
q = deque()
seen = [False] * n
dist = [-1] * n

def main():
    q.append(0)
    seen[0] = True
    dist[0] = 0
    while len(q) > 0:
        now_v = q.popleft()
        for new_v in G[now_v]:
            new_v -= 1
            if seen[new_v] is True:
                continue
            seen[new_v] = True
            q.append(new_v)

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

if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
u = int(input())
g = [[i for i in map(int, input().split())] for _ in range(u)]
graph = [[] for _ in range(u)]
ans = [-1] * u
for i in range(u):
    for j in range(g[i][1]):
        graph[i].append(g[i][2 + j] - 1)
que = deque()
que.append(0)
ans[0] = 0
while que:
    v = que.popleft()
    for nv in graph[v]:
        if ans[nv] != -1:
            continue
        ans[nv] = ans[v] + 1
        que.append(nv)

for i in range(u):
    print(i+1, ans[i])

Solution (Python):
from collections import deque

N = int(input())
tree = [[] for i in range(N)]

for _ in range(N):
    tmp = list(map(int, input().split()))
    for i in range(2, len(tmp)):
        tree[tmp[0]-1].append(tmp[i]-1)

q = deque(tree[0])
cnt = deque([1]*len(tree[0]))
s = {}
ans = [-1]*N

ans[0] = 0
s[0] = True
while len(q) != 0:
    g = q.popleft()
    c = cnt.popleft()
    if ans[g] == -1:
        ans[g] = c
        s[g] = True

    for tmp in tree[g]:
        if not(tmp in s):
            q.append(tmp)
            cnt.append(c+1)

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

Solution (Python):
from collections import deque

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

d = [-1] * (n+1)
visited = [False] * (n+1)

d[1] = 0
visited[1] = True
que = deque([1])
while len(que) > 0:
    c = que.popleft()
    for i in range(1, u[c][0]+1):
        if not visited[u[c][i]]:
            que.append(u[c][i])
            visited[u[c][i]] = True
            d[u[c][i]] = d[c] + 1

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

Solution (Python):
from collections import deque

N = int(input())                            

conj = [[] for _ in range(N)]
for i in range(N):                          
    L = list(map(int, input().split()))
    for a in L[2:]:
        conj[i].append(a-1)         

start = 0

visit = [False]*N                           
second_visit = [False]*N                    
next_set = deque()                          
next_set.append((start, 0))                 
visit[start] = True                         
res = [-1 for _ in range(N)]
res[0] = 0

while next_set:                             
    p, t = next_set.popleft()               
    for q in conj[p]:                       
        if not visit[q]:                    
            visit[q] = True                 
            res[q] = t + 1
            next_set.append((q, t + 1))     


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

Solution (Python):

import sys
import heapq

N = int(input())
G = []
for _ in range(N):
    u, k, *v = map(int, sys.stdin.readline().strip().split())
    v = [i - 1 for i in v]
    G.append(v)


distance = [-1] * N
q = []
fp = [True] * N  
heapq.heapify(q)
heapq.heappush(q, (0, 0))
fp[0] = False


while q:
    dist, u = heapq.heappop(q)
    distance[u] = dist
    for v in G[u]:
        if fp[v] is True:
            heapq.heappush(q, (dist + 1, v))
            fp[v] = False

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

Solution (Python):
from collections import deque
import sys

INFTY=sys.maxsize
WHITE=0
GRAY=1
BLACK=2

color=[]
d=[]
Q=deque([])
n=0
L=[]

def readinput():
    global n
    global L

    n=int(input())
    for i in range(n+1):
        L.append([])

    for i in range(n):
        inp=list(map(int,input().split()))
        L[inp[0]]=inp[2:]


def bfs(s):
    global color
    global d
    global Q

    for i in range(n+1):
        color=[WHITE]*(n+1)
        d=[-1]*(n+1)

    color[s]=GRAY
    d[s]=0
    Q.append(s)

    while(len(Q)>0):
        u = Q.popleft()
        for l in L[u]:
            if(color[l]==WHITE):
                color[l]=GRAY
                d[l]=d[u]+1
                Q.append(l)
        color[u]=BLACK

if __name__=='__main__':
    readinput()
    bfs(1)
    for i in range(1,n+1):
        print('{} {}'.format(i, d[i]))

Solution (Python):
from collections import deque
import sys


def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())


class Graph:
    def __init__(self, n, is_directed=False):
        """
        :param n: 頂点数
        :param is_directed: 有向グラフ(True)か無向グラフか(False)
        """
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.is_directed = is_directed

    def add_edge(self, u, v):
        """uからvへの(有向な)辺をつなぐ"""
        self.graph[u].append(v)
        if not self.is_directed:
            self.graph[v].append(u)

    def search(self, start, mode):
        '''開始地点から各頂点まで幅/深さ優先探索を行って得られた距離のリストを返す
        Args:
          start(int): 開始地点となる頂点
          mode(str): 幅優先探索(b)か深さ優先探索(d)を指定

        Returns:
          List[int]: 開始地点からの距離(未到達の場合は-1)
        '''
        dists = [-1] * self.n
        que = deque([start])
        dists[start] = 0
        if mode == 'b':
            get_v = que.popleft
        else:
            get_v = que.pop
        while que:
            now_v = get_v()
            for next_v in self.graph[now_v]:
                if dists[next_v] != -1:
                    continue
                que.append(next_v)
                dists[next_v] = dists[now_v] + 1
        return dists


n = I()
g = Graph(n, is_directed=True)
for _ in range(n):
    u, k, *v = LI()
    u -= 1
    if v == []:
        continue
    for vi in v:
        vi -= 1
        g.add_edge(u, vi)
res = g.search(0, 'b')
for i in range(n):
    print(i + 1, res[i])

Solution (Python):
N=int(input())
M=[input().split()[2:]for _ in[0]*N]
q=[0]
d=[0]+[-1]*N
while q:
 u=q.pop(0)
 for v in M[u]:
  v=int(v)-1
  if d[v]<0:d[v]=d[u]+1;q+=[v]
for i in range(N):print(i+1,d[i])

Solution (Python):
from collections import deque

n = int(input())
AL = [None for _ in range(n + 1)]
for i in range(1, n + 1):
    ukv = [int(x) for x in input().split()]
    AL[ukv[0]] = ukv[2:]

que = deque([1])
visited = [False] + [True] + [False] * (n - 1)
dist = [-1] + [0] + [-1] * (n - 1)
while que:
    u = que.popleft()
    for v in AL[u]:
        if visited[v]: continue
        dist[v] = dist[u] + 1
        visited[v] = True
        que.append(v)

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

Solution (Python):
import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
import copy

def bfs(start):
    d = [-1]*n
    d[start] = 0
    q = collections.deque([start])
    while q:
        p = q.popleft()
        next_v = edge[p]
        for v in next_v:
            if d[v] == -1:
                q.append(v)
                d[v] = d[p] + 1
    return d

if __name__ == "__main__":
    n = int(input())
    edge = []
    for i in range(n):
        u,k,*v_li = map(int,input().split())
        u-=1
        for j in range(len(v_li)):
            v_li[j] -= 1
        edge.append(v_li)
    ans = bfs(0)
    for i in range(n):
        print(i+1,ans[i])

Solution (Python):
from collections import deque


def main():
    while que:
        v, d = que.popleft()
        for nv in G[v]:
            nv -= 1
            if D[nv] == -1:
                D[nv] = D[v] + 1
                que.append((nv, D[nv]))
    for i in range(N):
        print(i+1, D[i])


if __name__ == "__main__":
    N = int(input())
    G = [[] for _ in range(N)]
    for _ in range(N):
        ipts = [int(ipt) for ipt in input().split()]
        G[ipts[0]-1] = ipts[2:]
    D = [-1]*N
    D[0] = 0
    que = deque()
    que.append((0, 0))
    main()

Solution (Python):
from collections import deque

N = int(input())

nodes = [tuple(map(int, input().split(' '))) for _ in range(N)]

distances = [-1] * (N + 1)

queue = deque()
queue.append((1, 0))

while len(queue) > 0:
    node, distance = queue.popleft()
    if distances[node] != -1:
        continue
    distances[node] = distance

    neighbors = nodes[node - 1][2:]
    for neighbor in neighbors:
        queue.append((neighbor, distance + 1))

for node in range(1, N + 1):
    print(node, distances[node])

Solution (Python):
from collections import deque
n=int(input())
l=[list(map(int,input().split())) for i in range(n)]
d=deque()
d.append(1)
check=[0]*n
check[0]=1
ans=[0]*n
kyori=[0]*n
while len(d)!=0:
  v=d.popleft()
  for i in l[v-1][2:]:
    if check[i-1]==0:
      check[i-1]=1
      ans[i-1]=(kyori[v-1]+1)
      kyori[i-1]=(kyori[v-1]+1)
      d.append(i)
for i in range(1,n):
  if ans[i]==0:
    ans[i]=-1
for i in range(n):
    print(i+1,ans[i])

Solution (Python):
from collections import deque

icase=0
if icase==0:
    n=int(input())
    u=[0]*n

    g = [[] for _ in range(n)]
    for i in range(n):
        ukv=list(map(int,input().split()))
        u[i]=ukv[0]-1
        ki=ukv[1]
        v=ukv[2:]
        for vi in v:
            g[u[i]].append(vi-1)

elif icase==1:
    n=4
    g = [[] for _ in range(n)]
    g[0]=[1,3]
    g[1]=[0,3]
    g[2]=[3]
    g[3]=[0,1,2]


q=deque([0])

stack=[0]
parent=[-1]*n
parent[0]=0
dist=[-1]*n
dist[0]=0
while q:
    state = q.popleft()

    for v in g[state]:


        if parent[v] !=-1:
            continue
        else:

            parent[v]=state
            dist[v]=dist[state]+1
            q.append(v)


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

Solution (Python):
from collections import deque
if __name__ == "__main__":
    n = int(input())
    graph = []
    for _ in range(n):
        v, k, *tmp = map(int, input().split())
        for j in range(len(tmp)):
            tmp[j] -= 1
        graph.append(tmp)
    visited = [False] * n
    qu = deque()
    qu.appendleft((0, 0))
    ans = [-1] * n
    visited[0] = True

    while qu:
        now, dis = qu.pop()
        ans[now] = dis

        for nei in graph[now]:
            if not visited[nei]:
                visited[nei] = True
                qu.appendleft((nei, dis + 1))
    for i in range(n):
        print(i+1,ans[i])

Solution (Python):

import queue


def printNode():
    for i, node in enumerate(glaph):
        print(i, node)


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


step = [-1]*(N+1)
step[1] = 0

q = queue.Queue()
q.put(1)
while not q.empty():
    now = q.get()
    next_node = glaph[now]

    for i in next_node:
        if step[i] != -1:
            continue
        q.put(i)
        step[i] = step[now] + 1

for i, v in enumerate(step):
    if i != 0:
        print(i, v)

Solution (Python):
from collections import deque


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


d = [-1] * n

que = deque()  


que.append(0)
d[0] = 0

while que:
    p = que.popleft()  
    for v in G[p]:
        v = int(v) - 1
        if d[v] < 0:  
            que.append(v)
            
            d[v] = d[p] + 1


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

Solution (Python):
n = int(input())
a = []
for i in range(n):
  tmp = list(map(int, input().split()))
  a.append(tmp[2:])
ans = [-1 for _ in range(n + 1)]
ans[1] = 0
que = [1]
while len(que) > 0:
  current = que.pop(0)
  if len(a[current - 1]) == 0:
    continue
  for next in a[current - 1]:
    if ans[next] == -1:
      que.append(next)
      ans[next] = ans[current] + 1
for i in range(1, n + 1):
  print(i, ans[i])

Solution (Python):
from collections import deque
n = int(input())
G = [[] for _ in range(n)]
for i in range(n):
    u, k, *vs = map(int, input().split())
    u -= 1
    vs = list(map(lambda x: x - 1, vs))
    for v in vs:
        G[u].append(v)

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

while len(que) > 0:
    now_v = que.popleft()
    now_dist = dist[now_v]
    next_vs = G[now_v]
    for next_v in next_vs:
        if dist[next_v] == -1:
            dist[next_v] = now_dist + 1
            que.append(next_v)

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

Solution (Python):
from collections import deque

N = int(input())
inf = 10 ** 6
graph = [[] for i in range(N)]
distance = [inf for i in range(N)]

for i in range(N):
  a = list(map(int,input().split()))
  a = list(map(lambda x: x - 1,a))
  k,n = a[0],a[1]
  if n >= 0:
    graph[k] = a[2:]
    

def bfs(path,root,dist):
  dist[root] = 0
  queue = deque([root])
  while queue:
    cur = queue.popleft()
    for chi in path[cur]:
      if dist[chi] == inf:
        queue.append(chi)
      dist[chi] = min(dist[cur] + 1,dist[chi])

bfs(graph,0,distance)
distance = [-1 if i == inf else i for i in distance]

for i,j in enumerate(distance):
  print(i + 1,j)

Solution (Python):
from collections import deque
n = int(input())

g = [[] for _ in range(n)]
for i in range(n):
    _, _, *edge = map(lambda x: int(x)-1, input().split())

    g[i] = edge

q = deque()
q.append(0)
dist = [-1 for _ in range(n)]
dist[0] = 0

while(len(q) > 0):
    v = q.popleft()

    for nv in g[v]:
        if(dist[nv] != -1): continue
        
        dist[nv] = dist[v] + 1
        q.append(nv)

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

Solution (Python):
import queue

def main():
    n = int(input())
    rows = []
    for i in range(n):
        rows.append([int(x) for x in input().split()])

    vum = {}
    for row in rows:
        u,k = row[0],row[1]
        ul = []
        if k > 0:
            for j in row[2:]:
                ul.append(j)
        vum.update({u:ul})
    

    
    q = queue.Queue()
    D = [-1]*n 
    s = 1 
    step = 0
    D[s-1] = step
    while True:
        
        step = D[s-1] + 1
        for v in vum[s]:
            
            if D[v-1] < 0:
                
                q.put(v)
                D[v-1] = step
        if q.empty():
            break
        
        s = q.get()

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

if __name__ == '__main__':
    main()