Go: package main

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

// I/O
type Scanner struct {
	sc *bufio.Scanner
}

func NewScanner() *Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1024), int(1e+9))
	return &Scanner{sc}
}

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

func (s *Scanner) nextInt() int {
	i, e := strconv.Atoi(s.nextStr())
	if e != nil {
		panic(e)
	}
	return i
}

func (s *Scanner) nextFloat() float64 {
	f, e := strconv.ParseFloat(s.nextStr(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func (s *Scanner) nextRuneSlice() []rune {
	return []rune(s.nextStr())
}

func (s *Scanner) nextIntSlice(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextInt()
	}
	return res
}

func (s *Scanner) nextFloatSlice(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextFloat()
	}
	return res
}

// Arithmetic
func max(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m < i {
			m = i
		}
	}
	return m
}

func min(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m > i {
			m = i
		}
	}
	return m
}

func abs(x int) int {
	if x > 0 {
		return x
	}
	return -x
}

func pow(x, y int) int {
	res := 1
	for i := 0; i < y; i++ {
		res *= x
	}
	return res
}

func ceil(a, b int) int {
	if a%b == 0 {
		return a / b
	} else {
		return a/b + 1
	}
}

// Sort
type RuneSlice []rune

func (a RuneSlice) Len() int           { return len(a) }
func (a RuneSlice) Less(i, j int) bool { return a[i] < a[j] }
func (a RuneSlice) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

// Main
type Queue struct {
	arr []int
}

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

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

func (q *Queue) isEmpty() bool {
	return len(q.arr) == 0
}

func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	N := sc.nextInt()
	G := make([][]int, N)
	for i := 0; i < N; i++ {
		u, k := sc.nextInt()-1, sc.nextInt()
		for j := 0; j < k; j++ {
			G[u] = append(G[u], sc.nextInt()-1)
		}
	}
	var q Queue
	seen := make([]int, N)
	for i := 0; i < N; i++ {
		seen[i] = -1
	}
	var search func(cur int)
	search = func(cur int) {
		for i := 0; i < len(G[cur]); i++ {
			next := G[cur][i]
			if seen[next] == -1 {
				q.push(next)
				seen[next] = seen[cur] + 1
			}
		}
	}
	q.push(0)
	seen[0] = 0
	for !q.isEmpty() {
		search(q.pop())
	}

	for i := 0; i < N; i++ {
		fmt.Fprintln(wtr, i+1, seen[i])
	}
	wtr.Flush()
}

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)

Python: # ALDS1_11_C.py
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:]
# printNode()

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

q = queue.Queue()
q.put(1)
while not q.empty():
    now = q.get()
    next_node = glaph[now]
#    print("now is ", now, ", next is", next_node)
    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)

Python: from collections import deque
n = int(input())
d = [-1]*n
d[0] = 0
M = []
for i in range(n):
    adj = list(map(int,input().split()))
    if adj[1] == 0:
        M += [[]]
    else:
        M += [adj[2:]]
Q = deque([0])

while Q != deque([]):
  u = Q.popleft()
  for i in range(len(M[u])):
    v = M[u][i]-1
    if d[v] == -1:
      d[v] = d[u] + 1
      Q.append(v)
for i in range(n):
  print(i+1,d[i])

Python: from __future__ import print_function
import time
from sys import stdin
from Queue import Queue
start = time.clock()
i = 0
num=int(stdin.readline())
L=[]
for _ in range(num):
    L.append([int(s) for s in stdin.readline().split()[2:]])
 
d=[-1]*num
d[0]=0
q=Queue(100)
q.put(0)
while not q.empty():
    u=q.get()
    for v in L[u]:
        if d[v-1]<0:
            d[v-1]=d[u]+1
            q.put(v-1)
for i,v in enumerate(d):
    print (i+1,v)

Python: n = int(raw_input())

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

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 = tuple([] 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 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 u in range(n):
    if colors[u] == Color.WHITE:
        d[u] = -1

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