Go: package main

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

var distance []int

type queue struct {
	q    []int
	head int
	tail int
}

func (q *queue) push(n int) {
	q.q[q.tail] = n
	q.tail++
}

func (q *queue) pop() int {
	q.head++
	return q.q[q.head-1]
}

func (q *queue) isEmpty() bool {
	return q.head == q.tail
}

func makeAdjList() [][]int {
	var n int
	fmt.Scanf("%d", &n)

	adj := make([][]int, n)
	for i := 0; i < n; i++ {
		adj[i] = make([]int, n)
	}

	sc := bufio.NewScanner(os.Stdin)
	for i := 0; i < n; i++ {
		sc.Scan()
		nodeInfo := strings.Split(sc.Text(), " ")
		outDegree, _ := strconv.Atoi(nodeInfo[1])

		if outDegree > 0 {
			for k := 0; k < outDegree; k++ {
				j, _ := strconv.Atoi(nodeInfo[k+2])
				j-- // convert 1 based to 0 based
				adj[i][j] = 1
			}
		}
	}

	return adj
}

func bfs(graph [][]int, s int) {
	distance = make([]int, len(graph))

	infty := -1
	for i := 0; i < len(distance); i++ {
		distance[i] = infty
	}
	distance[s] = 0

	q := &queue{make([]int, 1000), 0, 0}
	q.push(s)

	for !q.isEmpty() {
		u := q.pop()
		for i := 0; i < len(graph); i++ {
			if graph[u][i] == 0 {
				continue // u, i間に辺がない場合
			}
			if distance[i] != infty {
				continue // 訪問済みの場合
			}
			// 訪問するnodeの始点からの距離を設定し、訪問キューに入れる
			distance[i] = distance[u] + 1
			q.push(i)
		}
	}

	// print distance
	for i, d := range distance {
		fmt.Printf("%d %d\n", i+1, d)
	}
}

func main() {
	adj := makeAdjList()
	bfs(adj, 0)
}

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

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