Go: package main

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

type Pair struct {
	v int
	d int
}

type Queue []Pair

func (q *Queue) push(v Pair) {
	*q = append(*q, v)
}

func (q *Queue) pop() Pair {
	v := (*q)[0]
	*q = (*q)[1:]
	return v
}

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

	nVerts := scanInt(sc)
	graph := make([][]int, nVerts+1)

	for i := 0; i < nVerts; i++ {
		u := scanInt(sc)
		nDegrees := scanInt(sc)

		graph[u] = make([]int, nDegrees)
		for d := 0; d < nDegrees; d++ {
			graph[u][d] = scanInt(sc)
		}
	}

	paths := make([]int, nVerts+1)

	queue := Queue(make([]Pair, 0))
	queue.push(Pair{1, 1})
	paths[1] = 1

	for len(queue) > 0 {
		p := queue.pop()
		d := p.d + 1
		for _, v := range graph[p.v] {
			if paths[v] == 0 {
				paths[v] = d
				queue.push(Pair{v, d})
			}
		}
	}

	w := bufio.NewWriter(os.Stdout)
	for i := 1; i <= nVerts; i++ {
		fmt.Fprintf(w, "%d %d\n", i, paths[i]-1)
	}
	w.Flush()
}

func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	v, _ := strconv.Atoi(sc.Text())
	return v
}

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

Python: def MAIN():
    n = int(input())
    li = [[] for _ in range(n + 1)]
    ans = [[i, -1] for i in range(n + 1)]
    ans[1][1] = 0
    for _ in range(n):
        u, k, *v = map(int, input().split())
        li[u] = v
    dp = [1]
    while dp:
        u = dp.pop()
        for v in li[u]:
            if ans[v][1] == -1:
                ans[v][1] = ans[u][1] + 1
                dp.append(v)
    for d in ans[1:]:
        print(*d)
MAIN()

Python: import sys


def bfs(matrix):
    distances = [-1 for _ in range(len(matrix))]
    queue = [0]
    distances[0] = 0

    while 0 < len(queue):
        node_id = queue.pop(0)  # Dequeue
        distance = distances[node_id]
        for index, candidate in enumerate(matrix[node_id]):
            if candidate == 1 and distances[index] == -1:
                # ???????????¢????¨?????????????????????? node
                queue.append(index)
                distances[index] = distance + 1

    return distances

if __name__ == "__main__":
    # ??????????????????
    lines = [
        "4",
        "1 2 2 4",
        "2 1 4",
        "3 0",
        "4 1 3",
    ]
    # lines = sys.stdin.readlines()
    dimension = int(lines[0])
    matrix = [[0 for _ in range(dimension)] for _ in range(dimension)]

    # Set edge info
    for index, line in enumerate(lines[1:]):
        for edge in [int(x) for x in line.strip().split(" ")[2:]]:
            matrix[index][edge - 1] = 1

    distances = bfs(matrix)
    for index, distance in enumerate(distances):
        print("%d %d" % (index + 1, distance))

Python: T = [0]

def curshort(N,k,m,P,n):
    for i in range(1,n+1):
        if P[i]==-1 and N[k][i]==1:
            P[i] = m+1 
            curshort(N,i,m+1,P,n)

n = int(input())
A = [[0 for j in range(n+1)] for i in range(n+1)]


for i in range(n):
    vec = input().split()
    u = int(vec[0])
    k = int(vec[1])
    nodes = vec[2:]
    for i in range(int(k)):
        v = int(nodes[i])
        A[u][v] = 1

P=[-1 for i in range(n+1)]

P[1] = 0
curshort(A,1,0,P,n)
for i in range(1,n+1):
    print(i,P[i])

Python: # https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/11/ALDS1_11_C

from collections import deque

n = int(input())
graph = {}
res = [-1 for i in range(n + 1)]

for i in range(1, n + 1):
    data = input().split()
    graph[i] = [int(i) for i in data[2:]]

visited = set()
q = deque()
q.append((1, 0))  # node,distance
visited.add(1)

while q:
    node, dis = q.popleft()
    res[node] = dis
    for _next in graph[node]:
        if _next not in visited:
            visited.add(_next)
            q.append((_next, dis + 1))

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

Python: n = int(input())
G = [[] for i in range(n)] #G(i): 頂点iと隣接する頂点のlist
for i in range(n):
    a = [int(i) for i in input().split()]
    G[a[0]-1] = [i-1 for i in a[2:]]

d = [-1] * n
todo = [0]
d[0] = 0

while(todo != []):
    v = todo.pop(0)
    for i in G[v]:
        if d[i] == -1:
            d[i] = d[v]+1
            todo.append(i)

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

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

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 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
 
dis[0] = 0
for s in range(n):
    bfs_visit(s)
for s in range(n):
    if dis[s] == 99999:
       dis[s] = -1
for s in range(n):
    print (s+1, d[s])