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: import sys


def bfs(matrix):
    distances = [-1 for _ in range(len(matrix))]
    queue = [0]
    distances[0] = 0

    while 0 < len(queue):
        node_id = queue.pop(0)  # Dequeue
        distance = distances[node_id]
        for index, candidate in enumerate(matrix[node_id]):
            if candidate == 1 and distances[index] == -1:
                # ???????????¢????¨?????????????????????? node
                queue.append(index)
                distances[index] = distance + 1

    return distances

if __name__ == "__main__":
    # ??????????????????
    lines = [
        "4",
        "1 2 2 4",
        "2 1 4",
        "3 0",
        "4 1 3",
    ]
    # lines = sys.stdin.readlines()
    dimension = int(lines[0])
    matrix = [[0 for _ in range(dimension)] for _ in range(dimension)]

    # Set edge info
    for index, line in enumerate(lines[1:]):
        for edge in [int(x) for x in line.strip().split(" ")[2:]]:
            matrix[index][edge - 1] = 1

    distances = bfs(matrix)
    for index, distance in enumerate(distances):
        print("%d %d" % (index + 1, distance))

Python: T = [0]

def curshort(N,k,m,P,n):
    for i in range(1,n+1):
        if P[i]==-1 and N[k][i]==1:
            P[i] = m+1 
            curshort(N,i,m+1,P,n)

n = int(input())
A = [[0 for j in range(n+1)] for i in range(n+1)]


for i in range(n):
    vec = input().split()
    u = int(vec[0])
    k = int(vec[1])
    nodes = vec[2:]
    for i in range(int(k)):
        v = int(nodes[i])
        A[u][v] = 1

P=[-1 for i in range(n+1)]

P[1] = 0
curshort(A,1,0,P,n)
for i in range(1,n+1):
    print(i,P[i])

Python: # https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/11/ALDS1_11_C

from collections import deque

n = int(input())
graph = {}
res = [-1 for i in range(n + 1)]

for i in range(1, n + 1):
    data = input().split()
    graph[i] = [int(i) for i in data[2:]]

visited = set()
q = deque()
q.append((1, 0))  # node,distance
visited.add(1)

while q:
    node, dis = q.popleft()
    res[node] = dis
    for _next in graph[node]:
        if _next not in visited:
            visited.add(_next)
            q.append((_next, dis + 1))

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

Python: n = int(input())
G = [[] for i in range(n)] #G(i): 頂点iと隣接する頂点のlist
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])

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 = [99999 for i in range(n)]

def bfs_visit(s):
    for k in range(n):
      if a[s][k] == 1:
        if dis[k] > dis[s] + 1:
          dis[k] = dis[s] + 1
          bfs_visit(k)

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
 
dis[0] = 0
for s in range(n):
    bfs_visit(s)
for s in range(n):
    if dis[s] == 99999:
       dis[s] = -1
for s in range(n):
    print (s+1, d[s])

Python: # -*- coding:utf-8 -*-

def solve():
    import sys
    import heapq

    N = int(sys.stdin.readline())
    graph = []
    for _ in range(N):
        _in = list(map(int, sys.stdin.readline().split()))
        if len(_in) == 2:
            graph.append([])
            continue
        u, k, Vs = _in[0], _in[1], _in[2:]
        As = []
        for v in Vs:
            As.append(v-1)
        graph.append(As)

    dist = [float("inf") for _ in range(N)]
    dist[0] = 0
    que = []
    heapq.heappush(que, (0, 0))  # (頂点番号, 最短距離の候補)
    while que:
        u, d = heapq.heappop(que)
        if dist[u] < d: continue

        for v in graph[u]:
            if dist[v] > dist[u]+1:
                dist[v] = dist[u]+1
                heapq.heappush(que, (v, dist[v]))

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


if __name__ == "__main__":
    solve()

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

Python: import sys
from collections import deque


def bfs(s):
    flag_list[s] = 1
    d_list[s] = 0
    q.append(s)
    while len(q)>0:
        u = q.popleft()
        for v in range(n):
            if m_list[u][v] == 1 and flag_list[v] == 0:
                flag_list[v] = 1
                d_list[v] = d_list[u] + 1
                q.append(v)
        flag_list[u] = 2


if __name__ == "__main__":
    input = sys.stdin.readline
    n = int(input())
    m_list = [[0]*n for _ in range(n)]
    d_list = [-1]*n
    flag_list = [0]*n # 0: 未到達, 1: 処理中, 2: 完了
    q = deque([])
    for _ in range(n):
        input_list = list(map(int, input().split()))
        index = input_list[0] - 1
        if input_list[1] > 0:
            for a in input_list[2:]:
                m_list[index][a-1] = 1
    bfs(0)
    for i, d in enumerate(d_list):
        print(i+1, d_list[i])

Python: from collections import deque
from enum import Enum, auto

class Color(Enum):
    WHITE = auto()
    GRAY = auto()
    BLACK = auto()

n = int(input())
d = [0 for i in range(n)]
f = [0 for i in range(n)]

colors = [] # 頂点の訪問状態
A = [[0 for j in range(n)] for i in range(n)] # 隣接行列
queue = deque([])

# 隣接行列の初期化
for i in range(n):
    arr = list(map(int, input().split(' ')))
    u, k, v = arr[0], arr[1], arr[2:]
    for j in range(k):
        A[u-1][v[j]-1] = 1

def bfs_init():
    global colors
    colors = [Color.WHITE for i in range(n)]
    d[0] = 0
    bfs(0, 1)

def bfs(u, dist):
    global queue
    colors[u] = Color.GRAY

    for v in range(n):
        if A[u][v] == 1 and colors[v] == Color.WHITE:
            d[v] = dist
            queue.append(v)

    while len(queue) > 0:
        v = queue.pop()
        bfs(v, dist+1)

bfs_init()

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