Go: package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)

	g := make([][]int, n+1)
	d := make([]int, n+1)
	for i := 0; i < n; i++ {
		var u,k int
		fmt.Scan(&u)
		fmt.Scan(&k)
		g[u] = make([]int, k)
		for j := 0; j < k; j++ {
			fmt.Scan(&g[u][j])
		}

		d[i+1] = -1
	}

	q := [][]int{}
	q = append(q, []int{1, 0})
	for len(q) > 0 {
		pop := q[0]
		if len(q) > 1 {
			q = q[1:]
		} else {
			q = [][]int{}
		}
		if d[pop[0]] >= 0 {
			continue
		}
		d[pop[0]] = pop[1]

		for j := 0; j < len(g[pop[0]]); j++ {
			q = append(q, []int{g[pop[0]][j], pop[1]+1})
		}
	}

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

Python: from collections import deque

N = int(input())
tree = [[] for i in range(N)]

for _ in range(N):
    tmp = list(map(int, input().split()))
    for i in range(2, len(tmp)):
        tree[tmp[0]-1].append(tmp[i]-1)

q = deque(tree[0])
cnt = deque([1]*len(tree[0]))
s = {}
ans = [-1]*N

ans[0] = 0
s[0] = True
while len(q) != 0:
    g = q.popleft()
    c = cnt.popleft()
    if ans[g] == -1:
        ans[g] = c
        s[g] = True

    for tmp in tree[g]:
        if not(tmp in s):
            q.append(tmp)
            cnt.append(c+1)

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

Python: from collections import deque
import sys
input = sys.stdin.readline


N = int(input())
G = [[] for _ in range(N)]
for _ in range(N):
    ls = list(map(int, input().split()))
    u = ls[0] - 1
    for v in ls[2:]:
        G[u].append(v - 1)

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 v in range(N):
    print("{} {}".format(v + 1, dist[v]))

Python: from collections import deque

n = int(input())
g = [None] * (n+1)
ans = [0] * (n+1)

for _ in range(n):
    u,k,*vk = map(int,input().split())
    g[u] = vk

def bfs(now):
    que = deque()
    que.append(now)
    while que.__len__() != 0:
        now = que.popleft()
        for ne in g[now]:
            if ans[ne] != 0:
                continue
            ans[ne] = ans[now]+1
            que.append(ne)

bfs(1)
ans = [i if i != 0 else -1 for i in ans]
ans[1] = 0

print("\n".join("{} {}".format(*args) for args in zip(range(1, n+1), ans[1:])))

Python: import queue
N=int(input())
M=[list(map(int,input().split()[2:]))for _ in[0]*N]
q=queue.Queue();q.put(0)
d=[-1]*N;d[0]=0
while q.qsize()>0:
 u=q.get()
 for v in M[u]:
  v-=1
  if d[v]<0:d[v]=d[u]+1;q.put(v)
for i in range(N):print(i+1,d[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)
            except ValueError:
                return None

        visited = [0] * self.size
        first = 1
        depth = 0
        while first is not None:
            stack = [(first, depth, 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)
            except ValueError:
                return None

        visited = [0] * self.size
        first = 1
        depth = 0
        while first is not None:
            queue = [(first, depth)]
            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
                else:
                    continue
                j = 0
                while j < self.size:
                    try:
                        j = self._nodes[i].index(1, j+1)
                        queue.append((j, depth+1))
                    except ValueError:
                        break
                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

    for node in log.by_node():
        id_, find, dep, exit = node
        print("{} {}".format(id_, dep))


if __name__ == '__main__':
    run()

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

Python: from collections import deque

N = int(input())

edge = [[] for _ in range(N)]
for _ in range(N):
    t = list(map(int,input().split()))
    if t[1] != 0:
        edge[t[0]-1] = list(map(lambda x:int(x)-1, t[2:]))

dist = [-1]*N
dist[0] = 0
        
q = deque([0])
while q:
    now = q.popleft()
    for nxt in edge[now]:
        if dist[nxt] == -1:
            dist[nxt] = dist[now] + 1
            q.append(nxt)
        else:
            dist[nxt] = min(dist[nxt], dist[now] + 1)

for i,d in enumerate(dist):
    print(i+1, d)

Python: import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
import copy

def bfs(start):
    d = [-1]*n
    d[start] = 0
    q = collections.deque([start])
    while q:
        p = q.popleft()
        next_v = edge[p]
        for v in next_v:
            if d[v] == -1:
                q.append(v)
                d[v] = d[p] + 1
    return d

if __name__ == "__main__":
    n = int(input())
    edge = []
    for i in range(n):
        u,k,*v_li = map(int,input().split())
        u-=1
        for j in range(len(v_li)):
            v_li[j] -= 1
        edge.append(v_li)
    ans = bfs(0)
    for i in range(n):
        print(i+1,ans[i])