Go: package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

//util
var sc = bufio.NewScanner(os.Stdin)

func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func printList(list []int) {
	n := len(list)
	buf := bufio.NewWriter(os.Stdout)
	for _, v := range list[0 : n-1] {
		buf.Write([]byte(fmt.Sprintf("%d ", v)))
	}
	buf.Write([]byte(fmt.Sprintf("%d\n", list[n-1])))
	buf.Flush()
}

func max(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func min(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

//solve
const INFTY = (1 << 21)
const MAX = 100
const WHITE = 0
const GRAY = 1
const BLACK = 2

var time, n int

//隣接行列
var M [MAX][MAX]int

//d[i]: 頂点1から頂点iまでの距離
var color, d [MAX]int

func bfs(s int) {
	var q []int
	q = append(q, s)
	for i := 0; i < n; i++ {
		d[i] = INFTY
	}
	//sは開始点なので、0をいれる
	d[s] = 0

	//キューが空になるまで、以下を繰り返す
	for len(q) > 0 {
		u := q[0]
		q = q[1:]
		for v := 0; v < n; v++ {
			if M[u][v] == 0 {
				continue
			}
			if d[v] != INFTY {
				continue
			}
			d[v] = d[u] + 1
			q = append(q, v)
		}
	}

	for i := 0; i < n; i++ {
		fmt.Printf("%d ", i+1)
		if d[i] == INFTY {
			fmt.Printf("%d\n", -1)
		} else {
			fmt.Printf("%d\n", d[i])
		}
	}
}

func main() {
	sc.Split(bufio.ScanWords)
	n = nextInt()
	for i := 0; i < n; i++ {
		u, k := nextInt(), nextInt()
		M[u-1][u-1] = 0

		//fmt.Println(u, k)
		if k > 0 {
			for j := 0; j < k; j++ {

				v := nextInt()
				M[u-1][v-1] = 1

			}
		}

	}

	bfs(0)

}

Python: N= int(input())
E = [input().split()[2:] for _ in range(N)]
Q = [0]
L = [0] + [-1]*N
frag = [1] + [0]*N
def func(ide):
    global Q
    for i in E[ide]:
        i = int(i) - 1
        if frag[i] != 1:frag[i] = 1;L[i] = L[ide] +1 ;Q.append(i)
        
    

while Q:top = Q[0];func(top);del Q[0]

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

Python: #!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
4
1 2 2 4
2 1 4
3 0
4 1 3

output:
1 0
2 1
3 2
4 1
"""

import sys
from collections import deque

UNVISITED, VISITED_IN_QUEUE, POPPED_OUT = 0, 1, 2


def generate_adj_matrix(v_info):
    for v_detail in v_info:
        v_index, adj_num, *adj_list = map(int, v_detail)
        # assert len(adj_list) == adj_num
        init_adj_table[v_index].extend(adj_list)
    return init_adj_table


def graph_bfs(v_init):
    status[v_init] = VISITED_IN_QUEUE
    distance[v_init] = 0
    queue.appendleft(v_init)

    while queue:
        current = queue.popleft()
        for v in adj_table[current]:
            if status[v] is UNVISITED:
                status[v] = VISITED_IN_QUEUE
                distance[v] = distance[current] + 1
                queue.append(v)
        status[current] = POPPED_OUT
    return distance


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices_num = int(_input[0])
    vertices_info = list(map(lambda x: x.split(), _input[1:]))
    init_adj_table = [[] for _ in range(vertices_num + 1)]
    # assert len(vertex_info) == vertex_num

    # config length = (vertex_num + 1)
    queue = deque()
    status = [UNVISITED] * (vertices_num + 1)
    distance = [-1] * (vertices_num + 1)

    adj_table = generate_adj_matrix(vertices_info)
    ans = graph_bfs(1)
    for k, v in enumerate(ans[1:], 1):
        print(k, v)

Python: from sys import stdin
from collections import deque

def read_graph(n):
    A = [ [0]*(n+1) for _ in range(n+1) ]
    for _ in range(n):
        line = deque(stdin.readline().strip().split())
        i = line.popleft()
        line.popleft()
        for k in line:
            A[int(i)][int(k)] = 1
    return A

def bfs_ctrl(n, A):
    color = ["WHITE"] * (n+1)
    d = [-1] * (n+1)
    Q = deque([])

    def bfs(s):
        nonlocal color
        nonlocal d
        nonlocal Q
        color[s] = "GRAY"
        d[s] = 0
        Q.append(s)

        while Q:
            u = Q.popleft()
            for v in range(1, n+1):
                if A[u][v] and color[v] == "WHITE":
                    color[v] = "GRAY"
                    d[v] = d[u] + 1
                    Q.append(v)

            color[u] = "BLACK"

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

n = int(input())
A = read_graph(n)
bfs_ctrl(n, A)

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

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

Python: from collections import deque


def bfs(root):
    Q = deque()
    distance[root] = 0
    Q.append(root)
    i = root
    while len(Q) > 0:
        i = Q.popleft()
        for v in range(n):
            if adjMat[i][v] == 1 and color[v] == 'white':
                Q.append(v)
                color[v] = 'gray'
                distance[v] = distance[i] + 1
        color[i] = 'black'


n = int(input())
adjMat = [[0] * n for _ in range(n)]
color = ['white'] * n
distance = [-1] * n

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

bfs(0)

for i in range(n):
    out = ''
    out += '{} {}'.format(i + 1, distance[i])
    print(out)

Python: from collections import deque

n = int(input())                #エッジの個数
edge = [[] for _ in range(n)]   #エッジの隣接リスト（お隣さんを格納する）

for _ in range(n):
  u, _, *v = map(lambda x: int(x)-1, input().split())
  edge[u] = sorted(v)           #入力された隣接頂点をお隣さんリストに格納

dist = [-1] * n                #始点から各頂点iまでの距離を測るリスト
dist[0] = 0                    #0番目のエッジの距離
Q = deque([0])                 #次に訪問すべきエッジを記録するキュー

while len(Q):
  v = Q.popleft()             #vに次に訪問するエッジを代入（v=自分）
  for c in edge[v]:           #v(自分)のお隣さんの数分だけイテレーション
    if dist[c] == -1:         #もしお隣さんお距離が-1になっていたら
      dist[c] = dist[v] + 1   #お隣さんの距離=自分の距離+1にする
      Q.append(c)             #次に訪問すべきキューにお隣さんを代入

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

Python: n = int(raw_input())
 
G = [0 for i in range(n)] 
a = [[0 for i in range(n)] for j in range(n)]
dis = [-1 for i in range(n)]
dis[0] = 0
 
for i in range(n):
    G = map(int, raw_input().split())
    for j in range(G[1]):
        a[G[0]-1][G[2+j]-1] = 1
 
def bfs_visit(s):
    for k in range(n):
      if a[s][k] == 1 and dis[k] == -1:
         dis[k] = dis[s] + 1
         bfs_visit(k)

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

Python: n = int(input())
graph = [[0 for i in range(n)] for j in range(n)]
d = [0] * n
f = [0] * n
queue = [0]


for i in range(n):
   a = list(map(int, input().split()))
   for j in range(0, a[1], 1):
       graph[a[0] - 1][a[2 + j] - 1] = 1

while len(queue) != 0:
    i = queue.pop(0)
    for j in range(i, n):
        if (graph[i][j] == 1) & (f[j] == 0):
            queue.append(j)
            f[j] = 1
            d[j] = d[i] + 1

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