Go: package main

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

var scanner = bufio.NewScanner(os.Stdin)

func nextString() string {
	scanner.Scan()
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(nextString())
	if err != nil {
		fmt.Printf("strconv.Atoi failed: %v\n", err)
	}
	return n
}

func stringifyArray(arr []int) string {
	return strings.TrimRight(fmt.Sprintf("%+v", arr)[1:], "]")
}

var infty = 1000000000

type nodeKey int

type DirectedGraphNode struct {
	key       nodeKey
	adjacents []*DirectedGraphNode
	visited   bool
	d         int
	parent    *DirectedGraphNode
}

type DirectedGraph struct {
	nodes []DirectedGraphNode
}

func (g *DirectedGraph) setAdjacency(l, r nodeKey) {
	g.nodes[l].adjacents = append(g.nodes[l].adjacents, &g.nodes[r])
}

func newDirectedGraph(nNodes int) *DirectedGraph {
	graph := DirectedGraph{}
	graph.nodes = make([]DirectedGraphNode, nNodes)
	for iNodes := 0; iNodes < nNodes; iNodes++ {
		graph.nodes[iNodes].key = nodeKey(iNodes)

		graph.nodes[iNodes].visited = false
		graph.nodes[iNodes].d = infty
		graph.nodes[iNodes].parent = nil
	}
	return &graph
}

type QueueEntry struct {
	node *DirectedGraphNode
	next *QueueEntry
}

type Queue struct {
	head, tail *QueueEntry
}

func (q *Queue) enqueue(node *DirectedGraphNode) {
	entry := QueueEntry{}
	entry.node = node

	if q.tail == nil {
		q.head = &entry
		q.tail = &entry
		return
	}

	q.tail.next = &entry
	q.tail = q.tail.next
}

func (q *Queue) dequeue() *QueueEntry {
	if q.head == nil {
		return nil
	}
	poped := q.head
	q.head = q.head.next
	if q.head == nil {
		q.tail = nil
	}
	return poped
}

func (q *Queue) isEmpty() bool {
	return q.head == nil
}

func fillDistancesByBreadthFirstSearch(g *DirectedGraph, startNode *DirectedGraphNode) {
	startNode.visited = true
	startNode.d = 0

	queue := Queue{}
	queue.enqueue(startNode)
	for !queue.isEmpty() {
		u := queue.dequeue().node
		for _, adjacent := range u.adjacents {
			if !adjacent.visited {
				adjacent.visited = true
				adjacent.d = u.d + 1
				adjacent.parent = u
				queue.enqueue(adjacent)
			}
		}
		u.visited = true
	}
}

func main() {
	scanner.Split(bufio.ScanWords)

	nNodes := nextInt()
	g := newDirectedGraph(nNodes + 1)

	for iNode := 0; iNode < nNodes; iNode++ {
		nodeKeyLeft := nodeKey(nextInt())
		nAdj := nextInt()
		for iAdj := 0; iAdj < nAdj; iAdj++ {
			nodeKeyRight := nodeKey(nextInt())
			g.setAdjacency(nodeKeyLeft, nodeKeyRight)
		}
	}

	// fmt.Println(g)
	fillDistancesByBreadthFirstSearch(g, &g.nodes[1])
	// fmt.Println(g)

	for iNode := 1; iNode <= nNodes; iNode++ {
		node := g.nodes[iNode]
		distance := node.d
		if distance == infty {
			distance = -1
		}
		fmt.Println(node.key, distance)
	}
}

Python: class Queue:
  def __init__(self,c):
    self.values = [None]*(c+1)
    self.s = 0
    self.t = 0

  def push(self,x):
    if self._next(self.s) == self.t:
      raise Exception("Overflow")
    self.values[self.s] = x
    self.s = self._next(self.s)

  def pop(self):
    if self.s == self.t:
      raise Exception("Underflow")
    ret = self.values[self.t]
    self.t = self._next(self.t)
    return ret

  def size(self):
    if self.s >= self.t:
      return self.s-self.t
    else:
      return len(self.values) - (self.t-self.s)


  def _next(self,p):
    p += 1
    if p >= len(self.values):
      p = 0
    return p


def solve(G):
  d = {}
  n = len(G)
  for u in G:
    d[u] = -1
  d[1] = 0
  queue = Queue(n+1)
  queue.push(1)
  while queue.size() > 0:
    u = queue.pop()
    for v in G[u]:
      if d[v] == -1:
        d[v] = d[u] + 1
        queue.push(v)
  return d







n = int(input())
G = {}
for i in range(n):
  entry = list(map(int, input().split(' ')))
  u = entry[0]
  k = entry[1]
  G[u] = set()
  for v in entry[2:]:
    G[u].add(v)


d = solve(G)
for u in G:
  print(u,d[u])

Python: from collections import deque
n=int(input())
d=[-1]*(n+1)
d[1]=0
v=[[] for i in range(n+1)]
for i in range(n):
  a=list(map(int,input().split()))
  v[a[0]]=a[2:]
q=deque()
q.append(1)
while len(q)>0:
  curr=q.popleft()
  for i in v[curr]:
    if d[i]==-1:
      d[i]=d[curr]+1
      q.append(i)
for i in range(1,n+1):
  print(f'{i} {d[i]}')

Python: #!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin
from Queue import Queue
 
 
def main():
    num = int(stdin.readline())
 
    L = []
    for _ in xrange(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, v)
 
 
main()

Python: from collections import deque

n = int(input())
C = [[] for _ in range(n+1)]
for _ in range(n):
    stdin = list(map(int,input().split()))
    for j in range(stdin[1]):
        C[stdin[0]].append(stdin[2+j])

q = deque()
q.append(1)
d = [-1]*(n+1)
visited = [False]*(n+1)
d[1] = 0
visited[1] = True

while q:
    node = q.popleft()
    for adj in C[node]:
        if visited[adj] == False:
            q.append(adj)
            d[adj] = d[node]+1
            visited[adj] = True

for i in range(1,n+1):
    print("{} {}".format(i,d[i]))

Python: n=int(input())

lst=[0]*n

for _ in range(n):
    work=list(map(int,input().split()))
    lst[work[0]-1]=work[2:]

dis=[-1]*n
dis[0]=0
work=lst[0][:]
work_next=[]
token=0

while work:
    token+=1
    for x in work:
        if dis[x-1]==-1: dis[x-1]=token
        for y in lst[x-1]:
            if dis[y-1]==-1 : work_next.append(y)
    work=work_next[:]
    work_next=[]

for i in range(n):
    print("{} {}".format(i+1,dis[i]))

Python: import collections
N = int(input().strip())
Alst = []
for _ in range(N):
    u,k,*varray = map(int,input().strip().split(" "))
    Alst.append(varray)
D = [-1 for _ in range(N)]
D[0] = 0
Q = collections.deque()
Q.append(0)
while len(Q) > 0:
    cur = Q.popleft()
    for dst in range(N):
            if (dst+1 in Alst[cur]) and (D[dst] == -1):
                D[dst] = D[cur] + 1
                Q.append(dst)
for v in range(N):
    print(v+1,D[v])