Go: package main

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

//util
var sc = bufio.NewScanner(os.Stdin)

func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func printList(list []int) {
	n := len(list)
	buf := bufio.NewWriter(os.Stdout)
	for _, v := range list[0 : n-1] {
		buf.Write([]byte(fmt.Sprintf("%d ", v)))
	}
	buf.Write([]byte(fmt.Sprintf("%d\n", list[n-1])))
	buf.Flush()
}

func max(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func min(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

//solve
const INFTY = (1 << 21)
const MAX = 100
const WHITE = 0
const GRAY = 1
const BLACK = 2

var time, n int

//隣接行列
var M [MAX][MAX]int

//d[i]: 頂点1から頂点iまでの距離
var color, d [MAX]int

func bfs(s int) {
	var q []int
	q = append(q, s)
	for i := 0; i < n; i++ {
		d[i] = INFTY
	}
	//sは開始点なので、0をいれる
	d[s] = 0

	//キューが空になるまで、以下を繰り返す
	for len(q) > 0 {
		u := q[0]
		q = q[1:]
		for v := 0; v < n; v++ {
			if M[u][v] == 0 {
				continue
			}
			if d[v] != INFTY {
				continue
			}
			d[v] = d[u] + 1
			q = append(q, v)
		}
	}

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

func main() {
	sc.Split(bufio.ScanWords)
	n = nextInt()
	for i := 0; i < n; i++ {
		u, k := nextInt(), nextInt()
		M[u-1][u-1] = 0

		//fmt.Println(u, k)
		if k > 0 {
			for j := 0; j < k; j++ {

				v := nextInt()
				M[u-1][v-1] = 1

			}
		}

	}

	bfs(0)

}

Python: n = int(input())
G = {i:[] for i in range(1, n+1)}
for _ in range(n):
    ukv = list(map(int, input().split()))
    u = ukv[0]
    k = ukv[1]
    for i in range(2, 2+k):
        G[u].append(ukv[i])
        
stack = [1]
dist = [-1]*(n+1)
dist[1] = 0

while stack:
    target = stack.pop(0)
    for target_i in G[target]:
        if dist[target_i]==-1:
            dist[target_i] = dist[target]+1
            stack.append(target_i)
            
for i, dist_i in enumerate(dist[1:], 1):
    print(i, dist_i)

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 = [0] * 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.states[v]:
                    continue

                if self.dists[v] > self.dists[u] + 1:
                    self.dists[v] = self.dists[u] + 1
                queue.append(v)

                self.states[v] = 1

        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: n = int(input())

m = [[0 for _ in range(n+1)] for _ in range(n+1)]
mm = [[] for _ in range(n+1)]

for _ in range(n):
	tmp = [int(x) for x in input().split()]
	u,k,l = tmp[0],tmp[1],tmp[2:]
	mm[u] += tmp[2:]
	for x in l:
		m[u][x] = 1
		
dp = [float('inf') for _ in range(n+1)]
dp[1] = 0
queue = [1]

while queue:
	t = queue.pop(0)
	for x in mm[t]:
		if dp[x] > dp[t] + 1:
			dp[x] = dp[t] + 1
			queue.append(x)
		else:
			pass
			
for i,x in enumerate(queue):
	if i == 0:
		pass
	else:
		if x == float('inf'):
			print(i, -1)
		else:
			print(i, x)

Python: def BFS(G):
    ans = [0] + [[i+1,-1] for i in range(len(G))]
    def main(G,i,d):
        if -1 < ans[i][1] <= d: return
        ans[i] = [i, d]
        for j in G[i-1][2:]: main(G,j,d+1)
    main(G,1,0)
    return ans[1:]


if __name__=='__main__':
    n = int(input())
    G = [list(map(int,input().split())) for _ in range(n)]
    for out in BFS(G): print(*out)

Python: n = int(input())
 
adj = [None]
for i in range(n):
    adj_i = list(map(int, input().split()[2:]))
    adj.append(adj_i)
 
isSearched = [None] + [False] * n
 
distance = [None] + [-1] * n
 
def bfs(u):
    d = 0
    isSearched[u] = True
    distance[u] = d
    edge = [u]
    while edge:
        q = list(edge)
        edge = []
        d += 1
        for c_e in q:
            for n_e in adj[c_e]:
                if not isSearched[n_e]:
                    isSearched[n_e] = True
                    edge.append(n_e)
                    distance[n_e] = d
 
 
bfs(1)
 
for i, x in enumerate(distance[1:], start=1):
    print(i, x)

Python: n = int(input())

class Node:
    def __init__(self, idd, neighbors):
        self.idd = idd
        self.neighbors = neighbors
        self.dist = -1
        
    def __repr__(self):
        return "{0} {1}".format(self.idd, self.dist)
    
def breadthFirstSearch(Nodes):
    stack = [Nodes[0]]
    Nodes[0].dist = 0
    while len(stack) > 0:
        current = stack.pop(0)
        for v in current.neighbors:
            v_node = Nodes[v-1]
#             print('current:{}, v_node:{}'.format(current, v_node))
            if(v_node.dist == -1):
                v_node.dist = current.dist + 1
                stack.append(v_node)
            else:
                v_node.dist = v_node.dist if v_node.dist < current.dist + 1 else current.dist + 1
    return Nodes

Nodes = [None] * n
for i in range(n):
    row = [int(tt) for tt in input().split()]
    Nodes[row[0]-1] = Node(row[0], [ row[j + 2] for j in range(row[1])])

Nodes = breadthFirstSearch(Nodes)
for node in Nodes:
    print(node)

Python: from collections import deque


def get_next_node(node, discovery_time, adj_mat):
    for i, node in enumerate(adj_mat[node]):
        if discovery_time[i] == 0 and node == 1:
            return i
    return None

def bfs(node, adj_mat):
    distances = [-1] * len(adj_mat)

    distances[node] = 0
    q = deque(maxlen=len(adj_mat))
    q.append(0)
    while q:
        visit_node = q.popleft()
        for j in range(len(adj_mat)):
            if adj_mat[visit_node][j] and distances[j]==-1:
                distances[j] = distances[visit_node] + 1
                q.append(j)
    
    for i, d in enumerate(distances):
        print(i+1, d)


if __name__ == "__main__":
    n_node = int(input())
    # f = open('alds1_11_c-input.txt', 'r')
    # n_node = int(f.readline())

    adjacency_mat = [[0 for i in range(n_node)] for j in range(n_node)]
    for i in range(n_node):
        command = list(map(int, input().split()))
        # command = list(map(int, f.readline().split()))

        i = command.pop(0) - 1
        n_edge = command.pop(0)

        for j in command:
            adjacency_mat[i][j-1] = 1

    # f.close()
    discovery_time = [0] * n_node
    finish_time = [0] * n_node
    bfs(0, adjacency_mat)