Go: package main

import (
	"container/list"
	"fmt"
	"bufio"
	"os"
	"strconv"
)

const (
	N   = 100
	INF = 1 << 21
)

var (
	n        int
	adj      [N][N]int
	distance [N]int
)

func BFS(start int) {
	q := list.New()
	q.PushBack(start)
	for i := 0; i < n; i++ {
		distance[i] = INF
	}
	distance[start] = 0
	u := 0
	for q.Len() != 0 {
		u = q.Remove(q.Front()).(int)
		for v := 0; v < n; v++ {
			if adj[u][v] == 0 {
				continue
			}
			if distance[v] != INF {
				continue
			}
			distance[v] = distance[u] + 1
			q.PushBack(v)
		}
	}
	for i := 0; i < n; i++ {
		var d int
		if distance[i] == INF {
			d = -1
		} else {
			d = distance[i]
		}
		fmt.Printf("%d %d\n", i+1, d)
	}
}

func main() {
	var u, k, v int
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	n, _ = strconv.Atoi(scanner.Text())
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			adj[i][j] = 0
		}
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		u, _ = strconv.Atoi(scanner.Text())
		u -= 1
		scanner.Scan()
		k, _ = strconv.Atoi(scanner.Text())
		for j := 0; j < k; j++ {
			scanner.Scan()
			v, _ = strconv.Atoi(scanner.Text())
			v -= 1
			adj[u][v] = 1
		}
	}
	BFS(0)
}

Python: #!/usr/bin/env python3

import sys
# SimpleQueue でOKなのだが AOJ の環境では Python3.7 が使えない
from queue import Queue


class BFS():
    INFTY = sys.maxsize

    def __init__(self, M, n, debug=False):
        self.M = M
        self.n = n
        # 距離で訪問状態(color)を管理する
        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                  # 0 オリジンへ変換
        _ = inputs.pop(0)       # k （使わない...）
        for v in inputs:
            v -= 1              # 0 オリジンへ変換
            M[u][v] = 1

    BFS(M, n).bfs(0)


if __name__ == '__main__':
    main()

Python: import collections
n=int(input())
l=[]
for i in range(n):
  l1=list(map(int,input().split()))
  l2=[]
  if l1[1]==0:
    l2=["0" for j in range(n)]
  else:
    for j in range(n):
      if j+1 in l1[2:]:
        l2.append("1")
      else:
        l2.append("0")
  l.append(l2)
D=[-1 for i in range(n)]
D[0]=0
q=collections.deque()
q.append(0)
while len(q)!=0:
  cur=q.popleft()
  for d in range(n):
    if l[cur][d]=="1" and D[d]==-1:
      D[d]=D[cur]+1
      q.append(d)
for i in range(n):
  print(i+1,D[i])

Python: import queue,sys
N=int(input())
M=[list(map(int,e.split()[2:]))for e in sys.stdin]
q=queue.Queue();q.put(0)
d=[-1]*N;d[0]=0
while q.qsize()>0:
 u=q.get()
 for v in M[u]:
  v-=1
  if d[v]<0:d[v]=d[u]+1;q.put(v)
for i in range(N):print(i+1,d[i])

Python: # -*- coding: utf-8 -*-
from collections import deque

N = int(input())
adj = [[0]*N for _ in range(N)]
unsearched = set(range(1, N))
result = {n:-1 for n in range(N)}

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

que = deque([[0, 0]]) # edge distance


while len(que):
    q = que.pop()
    result[q[0]] = q[1]
    next_ = [[i, q[1] + 1] for i, a in enumerate(adj[q[0]]) if (a==1) & (i in unsearched)]
    unsearched = unsearched.difference([i[0] for i in next_])
    que.extendleft(next_)

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

Python: N=int(input())
M=[input().split()[2:]for _ in[0]*N]
q=[0]
d=[0]+[-1]*~-N
while q:
 u=q.pop()
 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])

Python: # Graph I - Breadth First Search
from collections import deque
def bfs(A,d):
    dq = deque()
    dq.append(0)
    d[0] = 0
    while len(dq):
        v = dq.pop()
        for i in range(len(A[v])-1,-1,-1):
            f = A[v][i]
            if f == 1 and d[i] == -1:
                d[i] = d[v] + 1
                dq.appendleft(i)

n = int(input())
A = []
for _ in range(n):
    ss = list(map(int, input().split()))
    u = ss[0] - 1
    row = [0 for _ in range(n)]
    for i in range(ss[1]):
        idx = 2 + i
        row[ss[idx]-1] = 1
    A.append(row)

d = [-1 for _ in range(n)]
bfs(A,d)

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

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])

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()  # ignore trailing spaces

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:
    #print(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])

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})
    # print(vum)

    ### bfs ###
    q = queue.Queue()
    D = [-1]*n # 最短距離
    s = 1 # 始点
    step = 0
    D[s-1] = step
    while True:
        # print('s',str(s))
        step = D[s-1] + 1
        for v in vum[s]:
            # print('v',str(v))
            if D[v-1] < 0:
                # print('append v',str(v),str(step))
                q.put(v)
                D[v-1] = step
        if q.empty():
            break
        # print(list(q.queue),V)
        s = q.get()

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

if __name__ == '__main__':
    main()

Python: import queue,sys
N=int(input())
M=[list(map(int,e.split()[2:]))for e in sys.stdin]
q=queue.Queue();q.put(0)
d=[-1]*N;d[0]=0
while q.qsize()>0:
 u=q.get()
 for v in M[u]:
  v-=1
  if d[v]<0:d[v]=d[u]+1;q.put(v)
for i in range(N):print(i+1,d[i])