Go: package main

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

type vertexId int

type vertex struct {
	id vertexId
	visitedAt int
	adjs []vertexId
}

func createVertex(id int, adjsInt []int) vertex {
	adjs := make([]vertexId, len(adjsInt))
	for i := 0; i < len(adjs); i++ {
		adjs[i] = vertexId(adjsInt[i])
	}
	return vertex{
		id: vertexId(id),
		visitedAt: -1,
		adjs: adjs,
	}
}

func (v *vertex) isVisited() bool {
	return v.visitedAt >= 0
}

func bfs(id vertexId, vqueue []vertexId, vertices []vertex) {
	vertex := &vertices[id-1]
	for _, vid := range vertex.adjs {
		if !vertices[vid-1].isVisited() {
			(&vertices[vid-1]).visitedAt = vertex.visitedAt+1
			vqueue = append(vqueue, vid)
		}
	}
	if len(vqueue) > 0 {
		nextId := vqueue[0]
		nextVqueue := vqueue[1:]
		bfs(nextId, nextVqueue, vertices)
	}
}

func solveBfs(vertices []vertex) {
	vertex := &vertices[0]
	vertex.visitedAt = 0
	vqueue := make([]vertexId, 0)
	bfs(vertex.id, vqueue, vertices)
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	n, err := nextInt(sc)
	if err != nil {
		panic(err)
	}

	vertices := make([]vertex, n)
	for i := 0; i < n; i++ {
		id, err := nextInt(sc)
		if err != nil {
			panic(err)
		}
		adjN, err := nextInt(sc)
		if err != nil {
			panic(err)
		}
		adjs := make([]int, adjN)
		for j := 0; j < adjN; j++ {
			adjId, err := nextInt(sc)
			if err != nil {
				panic(err)
			}
			adjs[j] = adjId
		}
		vertices[i] = createVertex(id, adjs)
	}

	solveBfs(vertices)

	for i := 0; i < n; i++ {
		fmt.Printf("%d %d\n", vertices[i].id, vertices[i].visitedAt)
	}
}

func nextText(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

func nextInt(sc *bufio.Scanner) (int, error) {
	return strconv.Atoi(nextText(sc))
}

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

Python: N = int(input())
G = [None for i in range(N)]
for i in range(N):
    u, k, *vs = map(int, input().split())
    G[u-1] = [e-1 for e in vs]


from collections import deque
dist = [-1]*N
que = deque([0])
dist[0] = 0
while que:
    v = que.popleft()
    d = dist[v]
    for w in G[v]:
        if dist[w] > -1:
            continue
        dist[w] = d + 1
        que.append(w)

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

Python: import abc


class AdjacentGraph:
    """Implementation adjacency-list Graph.
    Beware ids are between 1 and size.
    """
    def __init__(self, size):
        self.size = size
        self._nodes = [[0] * (size+1) for _ in range(size+1)]

    def set_adj_node(self, id_, adj_id):
        self._nodes[id_][adj_id] = 1

    def __iter__(self):
        self._id = 0
        return self

    def __next__(self):
        if self._id < self.size:
            self._id += 1
            return (self._id, self._nodes[self._id][1:])

        raise StopIteration()

    def dfs(self, handler=None):
        def find_first():
            try:
                return visited.index(0) + 1
            except ValueError:
                return None

        visited = [0] * self.size
        first = 1
        while first is not None:
            stack = [(first, 0, 0)]
            while len(stack) > 0:
                i, depth, j = stack.pop()
                if j == 0:
                    if handler:
                        handler.visit(i, depth)
                    visited[i-1] = 1
                    yield i
                try:
                    j = self._nodes[i].index(1, j+1)
                    stack.append((i, depth, j))
                    if visited[j-1] == 0:
                        stack.append((j, depth+1, 0))
                except ValueError:
                    if handler:
                        handler.leave(i)
            first = find_first()

    def bfs(self, handler=None):
        def find_first():
            try:
                return visited.index(0) + 1
            except ValueError:
                return None

        visited = [0] * self.size
        first = 1
        while first is not None:
            queue = [(first, 0)]
            while len(queue) > 0:
                (i, depth), *queue = queue
                if visited[i-1] == 0:
                    if handler:
                        handler.visit(i, depth)
                    visited[i-1] = 1
                    yield i
                    try:
                        j = 0
                        while j < self.size:
                            j = self._nodes[i].index(1, j+1)
                            if visited[j-1] == 0:
                                queue.append((j, depth+1))
                    except ValueError:
                        pass
                if handler:
                    handler.leave(i)
            first = find_first()


class EventHandler(abc.ABC):
    @abc.abstractmethod
    def visit(self, i, depth):
        pass

    @abc.abstractmethod
    def leave(self, i):
        pass


class Logger(EventHandler):
    def __init__(self, n):
        self.log = [(0, 0)] * n
        self.step = 0

    def visit(self, i, depth):
        self.step += 1
        self.log[i-1] = (self.step, depth, 0)

    def leave(self, i):
        self.step += 1
        self.log[i-1] = (self.log[i-1][0], self.log[i-1][1], self.step)

    def by_node(self):
        i = 1
        for discover, depth, finish in self.log:
            yield (i, discover, depth, finish)
            i += 1

def run():
    n = int(input())
    g = AdjacentGraph(n)
    log = Logger(n)

    for i in range(n):
        id_, c, *links = [int(x) for x in input().split()]
        for n in links:
            g.set_adj_node(id_, n)

    for i in g.bfs(log):
        pass

    reachable = None
    for node in log.by_node():
        id_, find, dep, exit = node
        if id_ > 1 and dep == 0:
            reachable = find - 1

        if reachable is not None and find > reachable:
            dep = -1

        print("{} {}".format(id_, dep))


if __name__ == '__main__':
    run()