Go: package main

import (
	"fmt"
	"os"
	"bufio"
	"strconv"
	"container/list"
)

const MaxNode int = 100

var d []int
var A [][]int
var N int
var l *list.List

func bfs(u int) {
	d[u] = 0
	l.PushBack(u)
	for ;l.Len() != 0; {
		u = l.Front().Value.(int)
		l.Remove(l.Front())
		for v:=0; v<N; v++ {
			if A[u][v] == 0 {
				continue
			}
			if d[v] != -1 {
				continue
			}
			d[v] = d[u] + 1
			l.PushBack(v)
		}
	}
}


func nextInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	num, _ := strconv.Atoi(scanner.Text())
	return num
}

func print() {
	for i:=0; i<N; i++ {
		fmt.Printf("%d %d\n", i+1, d[i])
	}
}

func initVariable() {
	d = make([]int, MaxNode)
	A = make([][]int, MaxNode)
	l = list.New()
	for i:=0; i<MaxNode; i++ {
		A[i] = make([]int, MaxNode)
		d[i] = -1
	}
}


func main() {
	initVariable()
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	N = nextInt(scanner)
	for i:=0; i<N; i++ {
		idx := nextInt(scanner)
		cnt := nextInt(scanner)
		for j:=0; j<cnt; j++ {
			node := nextInt(scanner)
			A[idx-1][node-1] = 1 
		}
	}
	bfs(0)
	print()
}

Python: # -*- coding: utf-8 -*-
from collections import deque


class Graph:
    def __init__(self, n, adj_matrix):
        self.n = n
        self.adj_matrix = adj_matrix

    def show(self):
        for _ in self.adj_matrix:
            print(*_)

    def dfs(self):
        self.states = [2] * self.n
        self.d = [None] * self.n
        self.f = [None] * self.n
        self.time = 0

        for u in range(self.n):
            if self.states[u] == 2:
                self.dfs_visit(u)

    def dfs_visit(self, u):
        self.states[u] = 1
        self.time += 1
        self.d[u] = self.time

        for v, edge in [(v, edge) for v, edge in enumerate(self.adj_matrix[u])
                        if edge]:
            if self.states[v] == 2:
                self.dfs_visit(v)

        self.states[u] = 0
        self.time += 1
        self.f[u] = self.time

    def show_dfs(self, start=0):
        self.dfs()
        for i, (d, f) in enumerate(zip(self.d, self.f)):
            print(i + 1, d, f)

    def bfs(self, start):
        self.states = [1] * self.n
        self.dists = [float('inf')] * self.n

        queue = deque([start])
        self.dists[start] = 0
        while queue:
            u = queue.popleft()
            edges = self.adj_matrix[u]

            for v, edge in [(v, edge) for v, edge in enumerate(edges) if edge]:
                if self.dists[v] > self.dists[u] + 1:
                    self.dists[v] = self.dists[u] + 1
                queue.append(v)

        self.dists = [
            -1 if dist == float('inf') else dist for dist in self.dists
        ]

    def show_bfs(self, start=0):
        self.bfs(start=start)
        for i, dist in enumerate(self.dists):
            print(i + 1, dist)


if __name__ == '__main__':
    n = int(input())
    adj_matrix = [[0] * n for i in range(n)]
    for i in range(n):
        for v in input().split()[2:]:
            adj_matrix[i][int(v) - 1] = 1

    g = Graph(n, adj_matrix)
    g.show_bfs()

Python: from collections import deque


def matrix(n):
    for _ in range(n):
        adj = list(map(int, input().split()))
        i = adj[0]
        v = adj[2:]
        for j in v:
            mat[i - 1][j - 1] = 1


def bfs(v):
    d[v] = 1
    dist[v] = 0
    dq.append(v)
    while dq:
        v = dq.popleft()
        for n, i in enumerate(mat[v]):
            if i == 1 and not d[n]:
                d[n] = 1
                dist[n] = dist[v] + 1
                dq.append(n)

n = int(input())
mat = [[0] * n for _ in range(n)]
d, dist = [0] * n, [-1] * n
dq = deque()
matrix(n)
bfs(0)
for i, v in enumerate(dist):
    print(i + 1, v)

Python: #AC

from collections import deque

n=int(input())
G=[[]]
for i in range(n):
    G.append(list(map(int,input().split()))[2:])

#bfs(木でないかも)
L=[-1]*(n+1)
q=deque()

L[1]=0
q.append(1)
while q:
    now=q.popleft()
    L.append(now)
    for next in G[now]:
        #探索済み
        if L[next]>=0:
            continue
        #探索予定(なくて良い)
        #if next in q:
        #    continue
        q.append(next)
        L[next]=L[now]+1

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

Python: #!/usr/bin/env python
# -*- coding: utf-8 -*-

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_adj_list = v_detail[2:]
        # assert len(v_adj_list) == int(v_detail[1])
        for each in v_adj_list:
            init_adj_matrix[int(v_detail[0]) - 1][int(each) - 1] = 1
    return init_adj_matrix


def graph_bfs(v_init):
    vertices_status_list[v_init] = VISITED_IN_QUEUE
    vertices_distance_list[v_init] = 0
    vertices_visit_queue.appendleft(v_init)

    while vertices_visit_queue:
        current_vertex = vertices_visit_queue.popleft()
        for v in range(1, vertices_num + 1):
            if adj_matrix[current_vertex - 1][v - 1] and vertices_status_list[v] is UNVISITED:
                vertices_status_list[v] = VISITED_IN_QUEUE
                vertices_distance_list[v] = vertices_distance_list[current_vertex] + 1
                vertices_visit_queue.appendleft(v)
        vertices_status_list[current_vertex] = POPPED_OUT
    return vertices_distance_list


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices_num = int(_input[0])
    vertices_info = list(map(lambda x: x.split(), _input[1:]))
    init_adj_matrix = [[0] * vertices_num for _ in range(vertices_num)]
    # assert len(vertex_info) == vertex_num

    # config length = (vertex_num + 1)
    vertices_visit_queue = deque()
    vertices_status_list = [UNVISITED] * vertices_num
    vertices_status_list.insert(0, -1)
    vertices_distance_list = [0] * (vertices_num + 1)

    adj_matrix = generate_adj_matrix(vertices_info)
    ans = graph_bfs(v_init=1)
    for j in range(vertices_num):
        print(j + 1, ans[j + 1])

Python: N = int(input())
edge = [[] for _ in range(N)]

for _ in range(N):
    l = list(map(int, input().split()))
    for j in range(l[1]):
        edge[l[0]-1].append(l[2+j]-1)


now_list = [0]
next_list = []
dist = 0
dists = [-1] * N
while len(now_list) > 0:
    for _ in range(len(now_list)):
        v = now_list.pop()
        if dists[v] == -1:
            dists[v] = dist
        else:
            continue
        for nv in edge[v]:
            next_list.append(nv)
    now_list = next_list
    next_list = []
    dist += 1

for i in range(N):
    print(1+i, dists[i])

Python: from collections import deque
import sys

INFTY=sys.maxsize
WHITE=0
GRAY=1
BLACK=2

color=[]
d=[]
Q=deque([])
n=0
L=[]

def readinput():
    global n
    global L

    n=int(input())
    for i in range(n+1):
        L.append([])

    for i in range(n):
        inp=list(map(int,input().split()))
        L[inp[0]]=inp[2:]


def bfs(s):
    global color
    global d
    global Q

    for i in range(n+1):
        color=[WHITE]*(n+1)
        d=[-1]*(n+1)

    color[s]=GRAY
    d[s]=0
    Q.append(s)

    while(len(Q)>0):
        u = Q.popleft()
        for l in L[u]:
            if(color[l]==WHITE):
                color[l]=GRAY
                d[l]=d[u]+1
                Q.append(l)
        color[u]=BLACK

if __name__=='__main__':
    readinput()
    bfs(1)
    for i in range(1,n+1):
        print('{} {}'.format(i, d[i]))

Python: import numpy as np
N= int(input())
frag, T, L, Q = np.zeros(N),np.zeros(N),np.zeros(N),[0]
# frag, T, L,Q = [0]*N, [0]*N, [0]*N, [0]
a = 100
frag[0] = 1
def func(ide):
#     print("frag = {}".format(frag))
    for i in E[ide]:
        i = int(i) - 1
        if frag[i] != 1:
            frag[i] = 1
            L[i] = L[ide] +1 
            Q.append(i) 
        else:
            return None
            


E = [input().split()[2:] for _ in range(N)]

while Q:
    top = Q[0]
    func(top)
    del Q[0]
for i in range(N):print(i + 1 ,int(L[i]))