Go: package main

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

type Queue []int

func (q *Queue) push(v int) {
	*q = append(*q, v)
}

func (q *Queue) pop() int {
	v := (*q)[0]
	*q = (*q)[1:]
	return v
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	nVerts := scanInt(sc)
	graph := make([][]int, nVerts+1)

	for i := 0; i < nVerts; i++ {
		u := scanInt(sc)
		nDegrees := scanInt(sc)

		graph[u] = make([]int, nDegrees)
		for d := 0; d < nDegrees; d++ {
			graph[u][d] = scanInt(sc)
		}
	}

	paths := make([]int, nVerts+1)

	queue := Queue(make([]int, 0))
	queue.push(1)
	paths[1] = 1

	for len(queue) > 0 {
		u := queue.pop()
		d := paths[u] + 1
		for _, v := range graph[u] {
			if paths[v] == 0 {
				paths[v] = d
				queue.push(v)
			}
		}
	}

	w := bufio.NewWriter(os.Stdout)
	for i := 1; i <= nVerts; i++ {
		fmt.Fprintf(w, "%d %d\n", i, paths[i]-1)
	}
	w.Flush()
}

func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	v, _ := strconv.Atoi(sc.Text())
	return v
}

Python: # -*- coding: utf-8 -*-
"""
Created on Sun Jul  8 10:56:33 2018

@author: maezawa
"""
n = int(input())
adj = [[] for _ in range(n)]
d = [-1 for _ in range(n)]
d[0] = 0


for j in range(n):
    ain = list(map(int, input().split()))
    u = ain[0]
    k = ain[1]
    for i in range(k):
        adj[u-1].append(ain[i+2]-1)
    adj[u-1].sort()
    #print(*adj[u-1])

stack = [0]

while stack:
    #print(stack)
    current = stack[-1]
    flag = 0
    for k in adj[current]:
        if d[k] < 0:
            d[k] = d[current]+1
            stack.append(k)
            flag = 1
        elif d[k] > d[current]+1:
            d[k] = d[current]+1
    if flag == 0:
        stack.pop()

    #print('current = {}, t = {}'.format(current, t))
    #print('stack', *stack)

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

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

Python: from collections import deque

# リストでグラフを表現する
n = int(input())
G = [input().split()[2:] for _ in range(n)]

# 頂点1から各頂点への距離を-1 (頂点1からたどり着けない)で初期化する
d = [-1] * n

que = deque()  # 訪問予定の頂点を格納する

# 初期状態をキューに入れる
que.append(0)
d[0] = 0

while que:
    p = que.popleft()  # FIFOでキューの要素を取り出し、その頂点を訪ねる。
    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])

Python: def bfs(graph, start, result):
    visited = {start: None}
    unvisited = [start]
    while unvisited:
        now = unvisited[0]
        unvisited = unvisited[1:]
        if visited[now] == None:
            result[now] = 0
        else:
            result[now] = result[visited[now]] + 1
        for next in graph[now][2:]:
            if not (next in visited):
                unvisited.append(next)
                visited[next] = now
    return visited

n = int(input())
g = [[]]
r = {i: -1 for i in range(n + 1)}

for i in range(n):
    g.append(list(map(int, input().split())))

v = bfs(g, 1, r)

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

Python: import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array

# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    visited = [-1] * N
    G = [[False] * N for _ in range(N)]
    for n in range(N):
        u, k, *V = il()
        for v in V:
            G[n][v - 1] = True

    que = queue.Queue()
    que.put(0)
    visited[0] = 0
    while not que.empty():
        now = que.get()
        for n in range(N):
            if G[now][n] and visited[n] == -1:
                visited[n] = visited[now] + 1
                que.put(n)

    for n in range(N):
        print(n + 1, visited[n])


if __name__ == '__main__':
    main()

Python: from collections import deque
n = int(input())
graph = [[] for _ in range(n)]
global Q, S, T
global visited, dis
Q = deque([0])
S = [0] #訪れた順
T = []
visited = [0 for _ in range(n)]
dis = [-1 for _ in range(n)] #初めからの距離
dis[0] = 0
def input_graph(n):
  for _ in range(n):
    node_id, num, *v = list(map(int, input().split()))
    for i in range(num):
      graph[node_id-1].append(v[i]-1)

def bfs(node_id):
  global Q, S
  while Q:
    node_id = Q.popleft()

    for ad_node in graph[node_id]:
      if visited[ad_node] == 1:
        continue
      visited[ad_node] = 1
      dis[ad_node] = dis[node_id] + 1
      S.append(ad_node)
      Q.append(ad_node)

if __name__ == "__main__":
  input_graph(n)
  bfs(0)
  for i, d in enumerate(dis):
    print(i+1, d)

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 graph_bfs(v_init):
    queue = deque()
    status[v_init] = VISITED_IN_QUEUE
    distance[v_init] = 0
    queue.appendleft(v_init)

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


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    v_num = int(_input[0])
    vertices = list(map(lambda x: x.split(), _input[1:]))
    # assert len(vertex_info) == vertex_num

    status = [UNVISITED] * (v_num + 1)
    distance = [-1] * (v_num + 1)

    adj_table = tuple([] for _ in range(v_num + 1))
    for v_info in vertices:
        v_index, adj_num, *adj_list = map(int, v_info)
        # assert len(adj_list) == adj_num
        adj_table[v_index].extend(adj_list)

    graph_bfs(v_init=1)
    for index, v in enumerate(distance[1:], 1):
        print(index, v)

Python: #!/usr/bin/python3

def find(id, V, d, dist):
    i = id - 1
    dist[i] = d
    for v in V[i]:
        if dist[v - 1] == -1:
            find(v, V, d + 1, dist)
    
n = int(input())
# [isFind, d, f]
A = [[False, 0, 0] for i in range(n)]
U = []
V = []
dist = [-1] * n
for i in range(n):
    l = list(map(int, input().split()))
    U.append(l[0])
    V.append(l[2:])

find(1, V, 0, dist)

for u in U:
    print(u, dist[u - 1])

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