Go: package main

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

type AdjacentList struct {
	matrix [][]int
}

func NewEmptyAdjacentList(dim int) *AdjacentList {
	matrix := make([][]int, dim)
	for i := 0; i < dim; i++ {
		matrix[i] = make([]int, dim)
	}
	return &AdjacentList{matrix: matrix}
}

func (al *AdjacentList) set(node int, adjacent int) {
	al.matrix[node-1][adjacent-1] = 1
}

func (al *AdjacentList) findAdjacentsFor(node int) []int {
	adjacents := []int{}
	for i, v := range al.matrix[node-1] {
		if v == 1 {
			adjacents = append(adjacents, i+1)
		}
	}
	return adjacents
}

type DistanceList struct {
	list []int
}

func NewDistanceList(dim int) *DistanceList {
	list := make([]int, dim)
	for i := 0; i < dim; i++ {
		list[i] = -1
	}
	return &DistanceList{list: list}
}

func (dl *DistanceList) set(node int, distance int) {
	dl.list[node-1] = distance
}

func (dl *DistanceList) get(node int) int {
	return dl.list[node-1]
}

func (dl *DistanceList) isVisited(node int) bool {
	return dl.list[node-1] >= 0
}

type Position struct {
	node     int
	distance int
}

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

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

	al := NewEmptyAdjacentList(dim)

	for i := 1; i <= dim; i++ {
		node, err := nextInt(sc)
		if err != nil {
			panic(err)
		}

		adjacentNum, err := nextInt(sc)
		if err != nil {
			panic(err)
		}
		for j := 0; j < adjacentNum; j++ {
			adjacent, err := nextInt(sc)
			if err != nil {
				panic(err)
			}
			al.set(node, adjacent)
		}
	}

	dl := NewDistanceList(dim)

	bfs(al, dl)

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

func bfs(al *AdjacentList, dl *DistanceList) {
	stack := []Position{Position{node: 1, distance: 0}}
	for len(stack) > 0 {
		currentPosition := stack[0]
		stack = stack[1:]
		if !dl.isVisited(currentPosition.node) {
			dl.set(currentPosition.node, currentPosition.distance)
		}
		for _, v := range al.findAdjacentsFor(currentPosition.node) {
			if !dl.isVisited(v) {
				stack = append(stack, Position{node: v, distance: currentPosition.distance + 1})
			}
		}
	}
}

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

Python: N=int(input())
List = [[] for i in range(N+1)]
for i in range(N):
    l=list(map(int,input().split()))
    List[l[0]]=l[2:]
#print(List)
D=[10**9 for i in range(N+1)]

Q=[[0,1]]
for i in range(10**9):
    if len(Q)==i:
        break
    if D[Q[i][1]]==10**9:
        D[Q[i][1]]=Q[i][0]
        for j in List[Q[i][1]]:
            if D[j]==10**9:
                Q.append([Q[i][0]+1,j])
for i in range(1,N+1):
    if D[i]==10**9:
        print(i,-1)
    else:
        print(i,D[i])

Python: import collections
n = int(input())
G = []
for i in range(n):
    T = [0]*n
    G.append(T)
for i in range(n):
    L = list(map(int,input().split()))
    for j in range(2,len(L)):
        G[i][L[j]-1] += 1
d = [float('inf')]*n
q = collections.deque()
q.append(0)
d[0] = 0
while len(q) > 0:
    start = q.popleft()
    for i in range(n):
        if G[start][i] == 1:
            if d[i] == float('inf'):
                q.append(i)
                d[i] = d[start]+1
for i in range(n):
    if d[i] != float('inf'):
        print(i+1,d[i])
    else:
        print(i+1,-1)

Python: n=int(input())
e=[[] for _ in range(n)]
for _ in range(n):
    u,_,*v=map(lambda x:int(x)-1, input().split())
    e[u]=sorted(v)
q=[0]
d=[-1]*n
d[0]=0
while q:
    i=q.pop(0)
    for v in e[i]:
        if d[v]==-1:
            q.append(v)
            d[v]=d[i]+1
for i in range(n):
    print(i+1,d[i])

Python: from sys import stdin
from collections import deque
n = int(input())
d = [-1] * (n + 1)
def bfs():
    d[1] = 0
    dq = deque([1])
    while len(dq) != 0:
        v = dq.popleft()
        for c in G[v]:
            if d[c] != -1 : continue
            d[c] = d[v] + 1
            dq.append(c)
    for i, x in enumerate(d[1:], start=1):
        print(i, x)
G = [0] + [list(map(int, inpput().split()[2:])) for i in range(n)]
bfs()

Python: n = int(raw_input())
  
G = [0 for i in range(n)] 
a = [[0 for i in range(n)] for j in range(n)]
dis = [99999 for i in range(n)]
dis[0] = 0
 
for i in range(n):
    G = map(int, raw_input().split())
    for j in range(G[1]):
        a[G[0]-1][G[2+j]-1] = 1
  
def bfs_visit(s):
    for k in range(n):
      if a[s][k] == 1:
       if dis[k] > dis[s]+1:
         dis[k] = dis[s]+1
         bfs_visit(k)
 
for s in range(n):
    bfs_visit(s)
for s in range(s):
    if dis[s] == 99999:
       dis[s] = -1
for s in range(n):
    print (s+1,dis[s])

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)
  bfs(0)
  for i, d in enumerate(dis):
    print(i, d)

Python: N= int(input());E = [input().split()[2:] for _ in range(N)]
frag, T, L,Q = [0]*N, [0]*N, [0]*N, [0]
a,frag[0] = 100, 1
def func(ide):
    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

while Q:top = Q[0];func(top);del Q[0]
for i in n:
    if L[i] == 0:
        L[i] == -1

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

Python: import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

INF = 100100100

class Queue:
    __slots__ = ['Q', 'begin', 'end']
    def __init__(self):
        self.Q = [None] * 100
        self.begin = 0
        self.end = 0
    def full(self) -> bool:
        if self.begin == 0 and self.end == 99:
            return True
        elif self.begin == self.end + 1:
            return True
        else:
            return False
    def empty(self) -> bool:
        if self.begin == self.end:
            return True
        else:
            return False
    def insert(self, num: int):
        if self.full():
            print('Error: Queue is full.')
        else:
            if self.end == 99:
                self.end = 0
            else:
                self.end += 1
            self.Q[self.end-1] = num
    def pop(self) -> int:
        if self.empty():
            print('Error: Queue is empty.')
            return
        else:
            if self.begin == 99:
                self.begin = 0
                return self.Q[99]
            else:
                self.begin += 1
                return self.Q[self.begin-1]

def bfs(M: list, visited: list, d: list, v: int = 0):
    n = len(visited)
    Q = Queue()
    visited[v] = True
    d[v] = 0
    Q.insert(v)
    while not Q.empty():
        u = Q.pop()
        for i in range(n):
            if M[u][i] == 1 and not visited[i]:
                visited[i] = True
                d[i] = d[u] + 1
                Q.insert(i)


def main():
    n = int(input())
    M = [[0]*n for _ in range(n)]
    for _ in range(n):
        a = list(map(int, input().split()))
        i = a[0]-1
        for j in range(a[1]):
            k = a[j+2]-1
            M[i][k] = 1
    visited = [False] * n
    d = [INF] * n
    bfs(M, visited, d)
    for i, l in enumerate(d):
        if l == INF:
            print(i+1, -1)
        else:
            print(i+1, l)

if __name__ == '__main__': main()