Go: package main

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

func main() {
	scn := bufio.NewScanner(os.Stdin)
	scn.Split(bufio.ScanWords)
	nextInt := func() int { scn.Scan(); r, _ := strconv.Atoi(scn.Text()); return r }
	w := bufio.NewWriter(os.Stdout)

	n := nextInt()
	vecs := make([][]int, n)
	for i := 0; i < n; i++ {
		u := nextInt()
		k := nextInt()
		for j := 0; j < k; j++ {
			vecs[u-1] = append(vecs[u-1], nextInt()-1)
		}
	}

	ds := make([]int, 0, n)
	for i := 0; i < n; i++ {
		ds = append(ds, -1)
	}

	q := make([]int, 0, n)
	q = append(q, 0)
	ds[0] = 0

	for len(q) > 0 {
		i := pop(&q)
		for _, v := range vecs[i] {
			if ds[v] == -1 {
				ds[v] = ds[i]+1
				q = append(q, v)
			}
		}
	}

	for i, d := range ds {
		fmt.Fprintln(w, i+1, d)
	}

	w.Flush()
}

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

Python: from queue import *

class Vertex:
	def __init__(self, u, k):
		self.u = u
		self.vertices = [0] * k
		self.d = -1
	def __str__(self):
		return str(self.u) + ' ' + str(self.d)

class Inf:
	def __init__(self,u,d):
		self.u = u
		self.d = d

def BFS(n, vertices):
	q = Queue()
	q.put(Inf(1,0))
	while q.empty() == False:
		inf = q.get()
		vertex = vertices[inf.u-1]
		if vertex.d == -1:
			vertex.d = inf.d
		else:
			vertex.d = min(vertex.d, inf.d)
		dist = inf.d + 1
		for i in range(len(vertex.vertices)):
			u = vertex.vertices[i]
			if vertices[u-1].d == -1:
				q.put(Inf(u, dist))
	
n = int(input())
vertices = []
for i in range(n):
	v = list(map(int, input().split()))
	u = v[0]
	k = v[1]
	vertex = Vertex(u, k)
	for j in range(k):
		vertex.vertices[j] = v[j+2]
	vertices.append(vertex)

BFS(n, vertices)
for i in range(n):
	print(str(vertices[i]))

Python: #coding:utf-8
        
def BFS(i,A,t):
    if i==1:
        return t
    else:
        for j in range(len(A)):
            if i in A[j]:
                return(BFS(j+1,A,t+1))
        return -1
            

if __name__=="__main__":
    n=int(input())
    A=[]
    for i in range(n):
        A.append(list(map(int,input().split(" ")))[2:])
    d=[0]*n
    t=0
    for i in range(n):
        d[i]=BFS(i+1,A,t)
    for i in range(n):
        print(i+1,d[i])

Python: from enum import Enum


class Bfs(object):
    """ Breadth First Search """
    class Status(Enum):
        """ ?????????????¨??????¶??? """
        white = 1  # ????¨????
        gray = 2  # ?¨???????
        black = 3  #?¨???????

    def __init__(self, data):
        num_of_nodes = len(data)+1
        self.color = [Bfs.Status.white] * (num_of_nodes + 1)  # ????????????????¨??????¶???
        self.S = []  # ?¨???????????????????????????¨???????????????
        self.M = self._make_matrix(data)  # data????????????????????£??\??????
        self.D = [-1] * (len(data) + 1)  # ????????????????????¢ (-1????????????????????°????????????)

    def _make_matrix(self, data):
        """ data(??£??\?????????)???????????£??\??????????????? (M[i][j]?????¢??§??????????????????+1??????????????????????????????) """
        num = len(data)
        graph_table = [[0] * (num+1) for _ in range(num+1)]
        for d in data:
            node_id = d[0]
            num_of_e = d[1]
            for e in d[2:]:
                graph_table[node_id][e] = 1
        return graph_table

    def search(self, start):
        """ start????????????????????????????????°??????????????? """
        self.S.append(start)
        self.color[start] = Bfs.Status.gray
        self.D[start] = 0  # ???????????§????????¢???0

        while self.S:
            u = self.S[-1]  # ?????¨?¨????????????????????????°??????
            self.S = self.S[:-1]  # pop()
            v = self._next(u)  # ?????¨???????????????????¬?????¨?????????????????????????
            while v != None:
                self.color[v] = Bfs.Status.gray
                self.S.append((v))  # ?¨??????????????????????????¬??????????????????? ???????????????????????????self.S[-1]?????????????????????
                self.D[v] = self.D[u] + 1
                v = self._next(u)


    def _next(self, node):
        """ ?¬?????¨???????????±???????????????????????????????????????????????¨??????????????????????????????? """
        edges = self.M[node]
        for i in range(1, len(edges)):
            if edges[i] == 1:
                if self.color[i] == Bfs.Status.white:
                    return i
        return None


if __name__ == '__main__':
    # ??????????????\???
    num = int(input())
    data = []
    for _ in range(num):
        data.append(list(map(int, input().split(' '))))

    # ???????????????
    # data[]????????????????????????1?????????????????£??\?????????????????????????´?????????????????????¨????????????????????????(??´???????????£??????????????????????????????)
    d = Bfs(data)
    d.search(1)

    # ???????????????
    for i in range(1, num+1):
        print('{0} {1}'.format(i, d.D[i]))

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)
  for i in range(n):
    if visited[i] == 1:
      continue
    visited[i] = 1
    bfs(i)
  for i, d in enumerate(dis):
    print(i, d)

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