Problem:
Breadth First Search Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$. Input In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format: $u$ $k$ $v_1$ $v_2$ ... $v_k$ $u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$. Constraints  $1 \leq n \leq 100$  Output For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs. Sample Input 1 4
1 2 2 4
2 1 4
3 0
4 1 3 Sample Output 1 1 0
2 1
3 2
4 1 Reference Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution (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) + 1
            except ValueError:
                return None

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

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

    reachable = None
    for node in log.by_node():
        id_, find, dep, exit = node
        if id_ > 1 and dep == 0:
            reachable = find - 1

        if reachable is not None and find > reachable:
            dep = -1

        print("{} {}".format(id_, dep))


if __name__ == '__main__':
    run()

Solution (Python):
n = int(input())

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

for _ in range(n):
    tmp = [int(x) for x in input().split()]
    u = tmp[0]
    k = tmp[1]
    l = tmp[2:]
    for x in l:
        m[u-1][x-1] = 1

dl = [float('inf') for _  in range(n)]
dl[0] = 0

q = [0]

while q:
    t = q.pop()
    tl = m[t]
    for i,x in enumerate(tl):
        if x == 1:
            if dl[i] > dl[t] + 1:
                q.append(i)
                dl[i] = dl[t] + 1
            else:
                pass
        else:
            pass


for i,x in enumerate(dl):
    if x == float('inf'):
        print(i+1, -1)
    else:
        print(i+1, x)

Solution (Python):
import sys
n = int(input())
input_line = [[int(i) for i in str.split()] for str in sys.stdin.read().splitlines()]
for i in range(n):
    input_line[i] = [] if len(input_line[i]) == 2 else input_line[i][2:]
is_visit = [False] * n
distance = [0] * n
queue = [1]

while len(queue) != 0:
    id = queue.pop(0)
    is_visit[id-1] = True
    for node_id in input_line[id-1]:
        if not is_visit[node_id-1]:
            distance[node_id-1] = distance[id-1] + 1
            queue.append(node_id)
            is_visit[node_id-1] = True

for i in range(n):
    d = distance[i] if is_visit[i] else -1
    print('{0} {1}'.format(i+1, d))

Solution (Python):
from collections import deque


def bfs(g, source):
    n = len(g)
    d = [float('inf') for _ in range(n)]
    d[0] = 0
    queue = deque()
    queue.append(0)
    while len(queue) > 0:
        cur = queue.popleft()
        for next in g[cur]:
            if d[cur] + 1 < d[next]:
                d[next] = d[cur] + 1
                queue.append(next)
    return d


def main():
    n = int(input())
    g = [[] for _ in range(n)]
    for _ in range(n):
        inp = list(map(int, input().split()))
        m = inp[0] - 1
        k = inp[1]
        for i in range(k):
            g[m].append(inp[i+2] - 1)
    d = bfs(g, 0)
    for i in range(n):
        if d[i] == float('inf'):
            d[i] = -1
        print(i+1, d[i])


if __name__ == '__main__':
    main()

Solution (Python):
n = int(input())

m = [[0 for _ in range(n+1)] 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:]
	
	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 i,x in enumerate(m[t]):
		if x == 1:
			if dp[i] > dp[t] + 1:
				dp[i] = dp[t] + 1
				queue.append(i)
			else:
				pass
		else:
			pass
			
for i,x in enumerate(dp):
	if i == 0:
		pass
	else:
		if x == float('inf'):
			print(i, -1)
		else:
			print(i, x)

Solution (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 i,x in enumerate(m[t]):
		if x == 1:
			if dp[i] > dp[t] + 1:
				dp[i] = dp[t] + 1
				queue.append(i)
			else:
				pass
		else:
			pass
'''

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)
			
for i,x in enumerate(dp):
	if i == 0:
		pass
	else:
		if x == float('inf'):
			print(i, -1)
		else:
			print(i, x)

Solution (Python):
n = int(input())

m = [[] 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:]
	m[u] += tmp[2:]
		
dp = [float('inf') for _ in range(n+1)]
dp[1] = 0
queue = [1]

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

Solution (Python):
def bfs(adj, s):
    n = len(adj)
    d = [-1 for _ in range(n)]
    c = [0 for _ in range(n)]

    d[s] = 0
    c[s] = 1

    queue = [s]

    while len(queue) > 0:
        u = queue.pop(0)
        for v in adj[u]:
            if c[v] == 0:
                c[v] = 1
                d[v] = d[u] + 1
                queue.append(v)

    return d


n = int(input())
adj = [[] for _ in range(n)]
for _ in range(n):
    s = [int(x) for x in input().split()]
    u = s[0]
    for v in s[2:]:
        adj[u - 1].append(v - 1)

d = bfs(adj, 0)

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

Solution (Python):
from collections import deque

n = int(input())
m = [[0 for j in range(n)] for i in range(n)]
color = [0 for i in range(n)]
q = deque()
dist = [-1 for i in range(n)]


def bfs(s):
    color[s], dist[s] = 1, 0
    q.append(s)

    while len(q) != 0:
        u = q.popleft()
        for v in range(n):
            if m[u][v] == 1 and color[v] == 0:
                color[v], dist[v] = 1, dist[u] + 1
                q.append(v)

        color[u] = 2


def main():
    for i in range(n):
        data = list(map(int, input().split()))
        for j in range(2, len(data)):
            m[data[0]-1][data[j]-1] = 1

    bfs(0)

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


if __name__ == '__main__':
    main()

Solution (Python):

n = int(input())
Q = [1]
M = [[False for i in range(n)] for j in range(n)]
dataList = []
for i in range(n):
    data = list(map(int,input().split()))
    dataList.append(data)
    for j in range(data[1]):
        v = data[j+2] - 1
        M[i][v] = True
color = ["white" for i in range(n)]
d = [-1 for i in range(n)]
d[0] = 0
while Q != []:
    u = Q.pop(0) - 1
    color[u] = "gray"
    data = dataList[u]
    for i in range(data[1]):
        v = data[i+2] - 1
        if M[u][v] == True and color[v] == "white":
            color[v] = "gray"
            d[v] = d[u] + 1
            Q.append(v+1)
    color[u] = "black"

for i,j in enumerate(d,1):
    print(i,j)

Solution (Python):
import sys

global status, d
status = {}
d=0

def bfs(keys, GRAPH, depth=0):
    global status
    if depth>10: quit

    buf =[]
    for e in keys:
        if status[e]==-1:
            status[e]=depth
            for e2 in GRAPH[e]:
                try:
                    if status[e2] == -1:
                        buf.append(e2)
                except:
                    pass
    if buf !=[]:
        bfs(buf, GRAPH, depth+1)
    return

n = int(raw_input())
x = {}
for i in range(n):
    seq = map(int,raw_input().split())
    key = seq[0]
    if key != 0:
        x[key] = seq[2:]
    else:
        x[key]=[]
    status[key] = -1

for e in x.keys():
    if e == 1:
        bfs([e], x)

for e in x.keys():
    print e, status[e]

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

Solution (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,v)

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

n = int(input())
graph = {i: deque() for i in range(1, n+1)}

for i in range(n):
    u, k, *v = map(int, input().split())
    v.sort()
    for vi in v:
        graph[u].append(vi)

seen = [0]*(n+1)
queue = deque()
dist = [-1]*(n+1)
def bfs(v):
    dist[v] = 0
    seen[v] = 1
    queue.append(v)
    while queue:
        q = queue[0]
        if not graph[q]:
            queue.popleft()
            continue
        g = graph[q].popleft()
        if seen[g]:
            continue
        seen[g] = 1
        dist[g] = dist[q] + 1
        queue.append(g)

bfs(1)
for id, d in enumerate(dist):
    if id == 0:
        continue
    print(id, d)

Solution (Python):
import collections

def breadth_first_search(g,check,length):
    q = collections.deque()
    q.append(1)
    check[1] = 1
    length[1] = 0
    while len(q) != 0:
        v = q.popleft()
        for u in g[v]:
            if check[u] == 0:
                check[u] = 1
                length[u] = length[v]+1
                q.append(u)

    return length

def main():
    N = int(input())
    g = []
    g.append([])
    for i in range(N):
        tmp = input().split()
        tmp_ls = []
        for i in range(int(tmp[1])):
            tmp_ls.append(int(tmp[i+2]))
        g.append(tmp_ls)

    check = [0]*(N+1)
    length = [0]*(N+1)
    ans = breadth_first_search(g,check,length)
    for i in range(N):
        node_num = i+1
        if ans[node_num] == 0 and i != 0:
            ans[node_num] = -1
        print(node_num,ans[node_num])

main()

Solution (Python):


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

Solution (Python):
from collections import deque

n = int(input())
graph = [[] for _ in range(n + 1)]
for _ in range(n):
    input_list = list(map(int, input().split()))
    index = input_list[0]
    num = input_list[1]

    if num >= 1:
        nodes = input_list[2:]
        for node in nodes:
            graph[index].append(node)
            

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

while q:
    index = q.popleft()
    
    for node in graph[index]:
        if visited[node] == -1:
            visited[node] = 1
            num[node] = num[index] + 1
            q.append(node)


for i, j in enumerate(num):
    if i == 0:
        continue
    print(i, j)

Solution (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:]

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

Solution (Python):
import sys
input = sys.stdin.readline

from collections import deque

def getNeighbor(A, i):
    a = len(A)
    for k in range(2, a):
        M[i][A[k]-1] = 1

def bfs():
    u = q.popleft()
    c[u] = 1

    for v in range(n):
        if M[u][v] and c[v] == 0:
            q.append(v)
            d[v] = d[u] + 1
            c[v] = 1

    if q:
        bfs()

    return

    bfs()

q = deque([0])

n = int(input())

c = [0] * n
d = [0] + [-1] * (n-1) 

M = [[0] * n for _ in range(n)]
t = 0

for i in range(n):
    A = list(map(int, input().split()))
    getNeighbor(A,i)

bfs()

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

Solution (Python):
import sys
import math
from collections import defaultdict, deque
    
input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]

def main():
    N = I()
    mylist = [[] for i in range(N)]
    for i in range(N):
        temp = LI()
        temp2 = temp[1]
        for j in range(temp2):
            mylist[temp[0]-1].append(temp[2+j]-1)
    
    d = [-1] * N
    d[0] = 0
    dq = deque()
    dq.append(0)
    while dq:
        now = dq.popleft()
        for next_p in mylist[now]:
            if d[next_p] == -1:
                d[next_p] = d[now]+1
                dq.append(next_p)
    for index, num in enumerate(d):
            print(index+1, num)
            
        
    
if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque

N = int(input())
graph = {i:[] for i in range(N)}

for i in range(N):
    g = list(map(int, input().split()))
    for j in range(g[1]):
        graph[g[0]-1].append(g[j+2]-1)
        
que = deque()
dist = [-1 for _ in range(N)]
que.append(0)
dist[0] = 0

while que:
    top = que.popleft()
    
    for i in graph[top]:
        if(dist[i] != -1):
            continue
        dist[i] = dist[top]+1
        que.append(i)

for i in range(len(dist)):
    print(i+1, dist[i])

Solution (Python):
import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array





sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    visited = [-1] * N
    G = [[False] * N for _ in range(N)]
    for n in range(N):
        u, k, *V = il()
        for v in V:
            G[n][v - 1] = True

    que = queue.Queue()
    que.put(0)
    visited[0] = 0
    while not que.empty():
        now = que.get()
        for n in range(N):
            if G[now][n] and visited[n] == -1:
                visited[n] = visited[now] + 1
                que.put(n)

    for n in range(N):
        print(n + 1, visited[n])


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

import sys
sys.setrecursionlimit(1000000)

N=int(input())
graph = [[] for _ in range(N)] 

for _ in range(N):
    v,c,*l = map(int,input().split())
    for i in l:
        graph[v-1].append(i-1)
        

dist=[-1]*N
dist[0]=0

d=deque()
d.append(0)

while d:
 
 v = d.popleft()
 for i in graph[v]:
   if dist[i] != -1:
     continue
   dist[i] = dist[v] + 1
   d.append(i)
for i in range(len(dist)):
    print(i+1,dist[i])

Solution (Python):
from collections import deque

n = int(input())
li = [list(map(int, input().split())) for _ in range(n)]

graph = [[] for _ in range(n+1)]
for u, k, *v in li:
    for i in v:
        graph[u].append(i)

ans = [-1] * (n+1)

ans[1] = 0
stack = deque([1])
while stack:
    num = stack.popleft()

    for s in graph[num]:
        if ans[s] == -1:
            stack.append(s)
            ans[s] = ans[num] + 1
            
for i, v in enumerate(ans[1:]):
    print(i+1, v)

Solution (Python):
INF = 10**18 + 7


def main():
    from collections import deque
    N = int(input())
    G = [[] for _ in range(N)]
    for _ in range(N):
        u, k, *A = (int(i)-1 for i in input().split())
        G[u] = A

    def bfs(s=0):
        que = deque([])
        dist = [INF]*N
        dist[s] = 0
        que.append(s)
        while que:
            pos = que.popleft()
            for v in G[pos]:
                if dist[v] != INF:
                    continue
                dist[v] = dist[pos] + 1
                que.append(v)
        return dist

    dist = bfs()
    for i, d in enumerate(dist, start=1):
        print(i, d if d != INF else -1)


if __name__ == '__main__':
    main()

Solution (Python):
import queue

n = int(input())

Graph = [[x-1 for x in list(map(int, input().split()))[2:]] for i in range(n)]










dist = [-1]*n
q = queue.Queue()

dist[0] = 0
q.put(0)

while not q.empty():
    v = q.get()

    for nv in Graph[v]:
        if dist[nv] != -1: continue

        dist[nv] = dist[v] + 1
        q.put(nv)


for v in range(n):
    print(v+1, dist[v])

Solution (Python):
from collections import deque

n = int(input())
graph = [list(map(int,input().split()))[2:] for _ in range(n)]

dist = [-1]*(n+1)
dist[0] = 0
dist[1] = 0
d = deque()
d.append(1)

while d:
    v = d.popleft()-1
    if len(graph[v]) >= 1:
        for i in graph[v]:
            if dist[i] == -1:
                dist[i] = dist[v+1]+1
                d.append(i)

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

Solution (Python):


from queue import Queue

N = int(input())
graph = [None]
for _ in range(N):
    graph.append(list(map(int, input().split(" ")))[1:])

class BFSSolver:

    def __init__(self, graph):
        self.graph = graph
        self.queue = Queue()
        self.queue.put(1)
        self.before_id = 1
        self.already_searched = [1]
        self.res = [0]
        for _ in range(N):
            self.res.append(-1)
        self.res[1] = 0
        self.turn = 0

    def next_turn(self):
        now_id = self.queue.get()
        before_id = now_id
        neighbors = self.graph[now_id][1:]
        for i in neighbors:
            if i not in self.already_searched:
                self.turn = self.res[before_id] + 1
                self.already_searched.append(i)
                self.res[i] = self.turn
                self.queue.put(i)

    def solve(self):
        while not self.queue.empty():
            self.next_turn()

        for id, i in enumerate(self.res[1:]):
            print("{} {}".format(id+1, i))

s = BFSSolver(graph)
s.solve()

Solution (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]

            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)

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

N = int(input())
G = [list(map(lambda x: int(x)-1, input().split()))[2:] for _ in range(N)]

D = [-1]*N
q = deque([[0, 0]])
while q:
    cur, dis = q.popleft()
    if D[cur] != -1: continue
    D[cur] = dis
    for nex in G[cur]:
        q.append([nex,dis+1])
for i in range(N):
    print(i+1, D[i])

Solution (Python):
from collections import deque
N = int(input())
edge = [[] for _ in range(N+1)]
for i in range(N):
  A = list(map(int, input().split()))
  edge[A[0]] = A[2:]

ans = [-1]*N
ans[0] = 0
d = deque([[1,0]])
while len(d)>0:
  v,dist = d.popleft()
  for w in edge[v]:
    if ans[w-1]==-1:
      ans[w-1]=dist+1
      d.append([w,dist+1])
for i in range(N):
  print(i+1,ans[i])

Solution (Python):


from collections import deque

n=int(input())
G=[[]]
for i in range(n):
    G.append(list(map(int,input().split()))[2:])


L=[-1]*(n+1)
q=deque()

L[1]=0
q.append(1)
while q:
    now=q.popleft()
    L.append(now)
    for next in G[now]:
        
        if L[next]>=0:
            continue
        
        
        
        q.append(next)
        L[next]=L[now]+1

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

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

Solution (Python):
from collections import deque

n = int(input())
adj = [[]]
for i in range(n):
    adj.append(list(map(int, input().split()))[2:])

ans = [-1]*(n+1)
ans[1] = 0

q = deque([1])
visited = [False] * (n+1)
visited[1] = True

while q:
    x = q.popleft()
    for y in adj[x]:
        if visited[y] == False:
            q.append(y)
            ans[y] = ans[x]+1
            visited[y] = True

for j in range(1, n+1):
    print(j, ans[j])

Solution (Python):
from collections import deque
n = int(input())
d = [-1]*n
d[0] = 0
M = []
for i in range(n):
    adj = list(map(int,input().split()))
    if adj[1] == 0:
        M += [[]]
    else:
        M += [adj[2:]]
Q = deque([0])

while Q != deque([]):
  u = Q.popleft()
  for i in range(len(M[u])):
    v = M[u][i]-1
    if d[v] == -1:
      d[v] = d[u] + 1
      Q.append(v)
for i in range(n):
  print(i+1,d[i])

Solution (Python):
from collections import deque

N = int(input())

Graph = {}
Node = []
visited = [-1]*(N)

for i in range(N):
    tmp = input().split()
    if int(tmp[1]) != 0:
        Graph[i] = [int(x)-1 for x in tmp[2:]]
    else:
        Graph[i] = []

queue = deque([0])
visited[0] = 0
while queue:
    x = queue.popleft()
    for i in Graph[x]:
        if visited[i] == -1:
            visited[i] = visited[x] + 1
            queue.append(i)

for i,j in enumerate(visited, 1):
    print(i, j)

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

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

N = int(input())
neighborlist = [None for _ in range(N+1)]
for _ in range(1, N+1):
    node, _, *L = list(map(int, input().split()))
    neighborlist[node] = L

distancelist = [-1]*(N+1)
queue = deque()
queue.append(1)
distancelist[1] = 0
while queue:
    node = queue.popleft()
    distance = distancelist[node]
    for neighbor in neighborlist[node]:
        if distancelist[neighbor] == -1:
            distancelist[neighbor] = distance + 1
            queue.append(neighbor)

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

Solution (Python):
from collections import defaultdict, deque

N = int(input())
edges = {}
scores = defaultdict(lambda: -1)

for _ in range(N):
    l = list(map(int, input().split()))
    node = l[0]
    degree = l[1]
    edges[node] = l[2:]

q = deque()
q.append((1, 0))

while q:
    node, score = q.popleft()
    if scores[node] != -1:
        continue
    scores[node] = score
    for child in edges[node]:
        q.append((child, score+1))

for node in range(1, N+1):
    print('%d %d' % (node, scores[node]))

Solution (Python):
import sys
from collections import defaultdict
from queue import Queue


def main():
    input = sys.stdin.buffer.readline
    n = int(input())
    g = defaultdict(list)
    for i in range(n):
        line = list(map(int, input().split()))
        if line[1] > 0:
            g[line[0]] = line[2:]
    q = Queue()
    q.put(1)
    dist = [-1] * (n + 1)
    dist[1] = 0
    while not q.empty():
        p = q.get()
        for nxt in g[p]:
            if dist[nxt] == -1:
                dist[nxt] = dist[p] + 1
                q.put(nxt)
    for i in range(1, n + 1):
        print(i, dist[i])


if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque

def bfs(x):
  for v in graph[x]:
    if dist[v] != -1:
      continue
    dist[v] = dist[x] + 1
    queue.append(v)
  if len(queue) == 0:
    return
  bfs(queue.popleft())
  
N = int(input())
graph = []
for _ in range(N):
  graph.append(list(map(lambda x: int(x)-1, input().split()))[2:])
dist = [-1] * N
queue = deque()

dist[0] = 0
bfs(0)
for i in range(N):
  print("{} {}".format(i+1, dist[i]))

Solution (Python):
import collections

N = int(input())
G = [[0 for _ in range(N)] for _ in range(N)]
for i in range(N):
    u,k,*varray = map(int,input().split())
    for v in varray:
        G[u-1][v-1] = 1
        
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 G[cur][dst] == 1 and D[dst] == -1:
            D[dst] = D[cur] + 1
            Q.append(dst)
for v in range(N):
    print(v+1, D[v])

Solution (Python):
from collections import deque
Q=deque()
n=int(input())
graph={}
d=[0 for i in range(n+1)]

for i in range(n):
    tmp=list(map(int,input().split()))
    graph[tmp[0]]=[0 for j in range(n+1)]
    for j in range(tmp[1]):
        graph[tmp[0]][tmp[2+j]]=1

Q.append(1)
while len(Q) is not 0:
    number=Q[0]
    if 1 in graph[number]:
        for i in range(graph[number].count(1)):
            Q.append(graph[number].index(1))
            if d[graph[number].index(1)] is 0:
                d[graph[number].index(1)]=d[number]+1
            graph[number][graph[number].index(1)]=0
        
    Q.popleft()

for i in range(n):
    if i==0:
        print(i+1,0)
    else:
        if d[i+1]==0:
            print(i+1,-1)
        else:
            print(i+1,d[i+1])

Solution (Python):
from collections import deque
n=int(input())
edge=[[] for _ in range(n+1)]
for i in range(n):
  v,k,*u=map(int,input().split())
  edge[v]=u
p=[-1]*(n+1)
p[1]=0
q=deque([])
q.append(1)
v=[1]*(n+1)
v[1]=0
while q:
  now=q.popleft()
  for i in edge[now]:
    if v[i]:
      q.append(i)
      p[i]=p[now]+1
      v[i]=0
for i in range(1,n+1):
  print(i,p[i])

Solution (Python):
from collections import deque
n = int(input())
data = [None]*n
for _ in range(n):
    a,*b = map(int,input().split())
    a -= 1
    data[a] = [i-1 for i in b[1:]]
d = [-1]*n
dq = deque([(0,0)])
while dq:
    p,q = dq.popleft()
    if d[p] == -1:
        d[p] = q
        for i in data[p]:
            dq.append((i,q+1))
for i,j in enumerate(d):
    print(i+1,j)