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):
n = int(raw_input())
INF = 10000000
queue = []

def bfs(s):
    queue.append(s)
    d = [INF for i in range(n)]
    d[s] = 0
    while len(queue) != 0:
        u = queue.pop(0)
        for v in range(n):
            if M[u][v] == 0:
                continue
            if d[v] != INF:
                continue
            d[v] = d[u] + 1
            queue.append(v)
    for i in range(n):
        if d[i] == INF:
            length = -1
        else:
            length = d[i]
        print "%d %d" %(i + 1, length)
        
M = [[0 for j in range(n)] for i in range(n)]
for i in range(n):
    tmp = map(int, raw_input().split())
    u = tmp[0]
    k = tmp[1]
    u -= 1
    for j in range(k):
        v = tmp[j + 2]
        v -= 1
        M[u][v] = 1
bfs(0)

Solution (Python):
def breathSerch(P,N):
    n=len(P)-1
    m=1
    QQ=[N[1]]
    while(QQ != []):
        R=[]
        for Q in QQ:
            for i in range(1,n+1):
                if Q[i]==1 and P[i]==-1:
                    P[i]=m
                    R.append(N[i])
        QQ = R
        m=m+1
    
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
breathSerch(P,A)
for i in range(1,n+1):
    print(i,P[i])

Solution (Python):
class Node(object):
    def __init__(self, V):
        self.V = V
        self.d = -1 
  
n = int(input())
nodes = [0] * 101
for i in range(n):
    data = input().split()
    V = list(map(int, data[2:]))
    V.sort(reverse = True)
    nodes[int(data[0])] = Node(V)
  
l = [1,]
l_old = []
cnt = 0

while len(l) > 0:
    l_old = l
    l = []
    for i in l_old:
        if nodes[i].d == -1:
            nodes[i].d = cnt
            V = nodes[i].V
            for j in V:
                if not j in l:
                    if nodes[j].d == -1:
                        l.append(j)
    cnt += 1
for i in range(1, n+1):
    if not isinstance(nodes[i], int):
        print(i, nodes[i].d)

Solution (Python):
from collections import deque
n = int(raw_input())

M = [[0]*n for _ in xrange(n)]
color = [0] * n
WHITE = 0
GRAY = 1
BLACK = 2
d = [-1] * n
Q = deque([])

def bfs():
    color[0] = GRAY
    d[0] = 0
    Q.append(0)
    while len(Q) > 0:
        u = Q.popleft()
        for v in xrange(n):
            if M[u][v] == 1 and color[v] == WHITE:
                color[v] = GRAY
                d[v] = d[u] + 1
                Q.append(v)
        color[u] = BLACK
    for u in xrange(n):
        print "{} {}".format(u+1, d[u])
    return

def main():
    for i in xrange(n):
        a = map(int, raw_input().split())
        u = a[0]-1
        k = a[1]
        for j in xrange(k):
            v = a[j+2] -  1
            M[u][v] = 1
    
    bfs()
    return 0

main()

Solution (Python):
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
n = int(raw_input())
  
d = [99999 for i in range(n)]
G = [0 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]
  
def BFS(s):
    for e in range(n):
        if M[s][e] == 1:
            if d[e] > d[s] + 1:
                d[e] = d[s]+1
                BFS(e)
  
for i in range(n):
    G = map(int, raw_input().split())
    for j in range(G[1]):
        M[G[0]-1][G[2+j]-1] = 1
  
d[0] = 0
for s in range(n):
        BFS(s)
for s in range(n):
    if d[s] == 99999:
        d[s] = -1
for s in range(n):
    print'{0} {1}'.format(s+1, d[s])

Solution (Python):
from collections import deque
V = int(input())
edge = [[] for _ in range(V)]
for _ in range(V):
    u, _, *v = map(lambda x: int(x)-1, input().split())
    edge[u] = sorted(v)
dist = [-1] * V
dist[0] = 0
que = deque([0])

while len(que):
    v = que.popleft()
    for c in edge[v]:
        if dist[c] == -1:
            dist[c] = dist[v] + 1
            que.append(c)
for i, d in enumerate(dist):
    print(i+1, d)

Solution (Python):
from collections import deque
V = int(input())
edge = [[] for _ in range(V)]
for _ in range(V):
    u, _, *v = map(lambda x: int(x)-1, input().split())
    edge[u] = v
dist = [-1] * V
dist[0] = 0
que = deque([0])

while len(que):
    v = que.popleft()
    for c in edge[v]:
        if dist[c] == -1:
            dist[c] = dist[v] + 1
            que.append(c)
for i, d in enumerate(dist):
    print(i+1, d)

Solution (Python):
from collections import deque


def matrix(n):
    for _ in range(n):
        adj = list(map(int, input().split()))
        i = adj[0]
        v = adj[2:]
        for j in v:
            mat[i - 1][j - 1] = 1


def bfs(v):
    d[v] = 1
    dist[v] = 0
    dq.append(v)
    while dq:
        v = dq.popleft()
        for n, i in enumerate(mat[v]):
            if i == 1 and not d[n]:
                d[n] = 1
                dist[n] = dist[v] + 1
                dq.append(n)

n = int(input())
mat = [[0] * n for _ in range(n)]
d, dist = [0] * n, [-1] * n
dq = deque()
matrix(n)
bfs(0)
for i, v in enumerate(dist):
    print(i + 1, v)

Solution (Python):
def bfs():
    while q!=[]:
        color[q[0]-1]="grey"
        for i in m[q[0]-1]:
            if i==0:continue
            if color[i-1]=="white":
                color[i-1]="grey"
                q.append(i)
                d[i-1]=d[q[0]-1]+1
        del q[0]

n=input()
d=[0]*n
m=[[0]*n for _ in xrange(n)]
info=[0]*n
color=["white"]*n
for i in xrange(n):
    info[i]=map(int,raw_input().split())
    if info[i][1]==0:
        pass
    else:
       for j in info[i][2:]:
           m[info[i][0]-1][j-1]=j
q=[1]
bfs()
for i in xrange(n):
    if i!=0 and d[i]==0:
        print i+1,-1
    else:
        print i+1,d[i]

Solution (Python):
import sys

def bfs():
    global V, D

    D[1] = 0
    children = V[1]
    d = 1
    while len(children) != 0 :
        new = []
        for child in children:
            if D[child] == -1:
                D[child] = d
                new += V[child]
        children = new
        d += 1

lines = sys.stdin.readlines()
n = int(lines[0])
V = [[] for _ in range(n + 1)]

for i in range(1, n + 1):
    v = map(int, lines[i].split())
    V[v[0]] = v[2:]
D = [-1] * (n + 1)
bfs()

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

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

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

import collections

def bfs(u):
    isSearched[u] = True
    distance[u] = 0
    edge = collections.deque()
    edge.append(u)
    while edge:
        c_e = edge.popleft()
        for n_e in adj[c_e]:
            if not isSearched[n_e]:
                isSearched[n_e] = True
                distance[n_e] = distance[c_e] + 1
                edge.append(n_e)


bfs(1)

for i, x in enumerate(distance[1:], start=1):
    print(i, x)

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

import collections

def bfs(u):
    isSearched[u] = True
    distance[u] = 0
    edge = collections.deque()
    edge.append(u)
    while edge:
        c_e = edge.popleft()
        for n_e in adj[c_e]:
            if not isSearched[n_e]:
                isSearched[n_e] = True
                distance[n_e] = distance[c_e] + 1
                edge.append(n_e)


bfs(1)

for i, x in enumerate(distance[1:], start=1):
    print(i, x)

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

Solution (Python):
import Queue
class Node:
    def __init__(self,v):
        self.v = v
        self.c = []

def bfs(n):
    d = {n.v:0}
    q = Queue.Queue()
    q.put(n)
    visited = set([n.v])
    while q.qsize() > 0:
        x = q.get()
        for c in x.c:
            if not c.v in visited:
                q.put(c)
                d[c.v] = d[x.v]+1
                visited.add(c.v)
    return d



n = int(raw_input())
nodes = {}
for _ in range(n):
    entry = map(int,raw_input().split(' '))
    nid = entry[0]
    if not nid in nodes: nodes[nid] = Node(nid)
    k = entry[1]
    if k > 0:
        children = entry[2:]
        for c in children:
            if not c in nodes: nodes[c] = Node(c)
            nodes[nid].c.append(nodes[c])

d = bfs(nodes[1])
for nid in nodes:
    if not nid in d:
        d[nid] = -1
for k in d:
    print k,d[k]

Solution (Python):
n = int(input())
 
adj = [None]
for i in range(n):
    adji = list(map(int, input().split()[2:]))
    adj.append(adji)
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 ce in q:
            for ne in adj[ce]:
                if not isSearched[ne]:
                    isSearched[ne] = True
                    edge.append(ne)
                    distance[ne] = d
BFS(1)
for i, x in enumerate(distance[1:], start=1):
    print(i, x)

Solution (Python):


level = False
def debug(v):
    if level:
        print(v)

NOT_FOUND = 0
ENQUEUED = 1
FOUND = 2

def bfs(graph, status, results):
    queue = []
    queue.append(1)
    while len(queue) != 0:
        node = queue.pop(0)
        status[node] = FOUND
        d = results[node]
        for edge in graph[node]:
            if status[edge] != NOT_FOUND:
                continue
            status[edge] = ENQUEUED
            queue.append(edge)
            results[edge] = d + 1

    return results

if __name__ == "__main__":
    n = int(input())
    status = [NOT_FOUND] * (n + 1)
    results = [-1] * (n + 1)
    results[1] = 0
    g = [[0]]

    for i in range(n):
        row = [int(x) for x in input().split()]
        row.pop(0)
        row.pop(0)
        g.append(row)

    bfs(g, status, results)
    results.pop(0)

    for idx, v in enumerate(results):
        print(idx + 1, v)

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

g = {}
for i in range(n):
    x = list(map(int, input().split()))
    g[x[0]] = [x[2:], 'w', x[0], None]

q = queue.Queue()
node = g[1]
node[-1] = 0
node[1] = 'g'
q.put(node)

while not q.empty():
    node  = q.get()
    d = node[-1] + 1
    for i in node[0]:
        ch = g[i]
        if ch[1] == 'w':
            ch[-1] = d
            ch[1] = 'g'
            q.put(ch)

for i in range(n):
    node = g[i+1]
    if node[-1] == None:
        d = -1
    else:
        d = node[-1]
    print("{} {}".format(i+1, d))

Solution (Python):



import sys
from collections import deque

UNVISITED, VISITED_IN_QUEUE, POPPED_OUT = 0, 1, 2


def generate_adj_matrix(v_info):
    for v_detail in v_info:
        v_adj_list = v_detail[2:]
        
        for each in v_adj_list:
            init_adj_matrix[int(v_detail[0]) - 1][int(each) - 1] = 1
    return init_adj_matrix


def graph_bfs(v_init):
    vertices_status_list[v_init] = VISITED_IN_QUEUE
    vertices_distance_list[v_init] = 0
    vertices_visit_queue.appendleft(v_init)

    while vertices_visit_queue:
        current_vertex = vertices_visit_queue.popleft()
        for v in range(1, vertices_num + 1):
            if adj_matrix[current_vertex - 1][v - 1] and vertices_status_list[v] is UNVISITED:
                vertices_status_list[v] = VISITED_IN_QUEUE
                vertices_distance_list[v] = vertices_distance_list[current_vertex] + 1
                vertices_visit_queue.append(v)
        vertices_status_list[current_vertex] = POPPED_OUT
    return vertices_distance_list


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices_num = int(_input[0])
    vertices_info = list(map(lambda x: x.split(), _input[1:]))
    init_adj_matrix = [[0] * vertices_num for _ in range(vertices_num)]
    

    
    vertices_visit_queue = deque()
    vertices_status_list = [UNVISITED] * vertices_num
    vertices_status_list.insert(0, -1)
    vertices_distance_list = [-1] * (vertices_num + 1)

    adj_matrix = generate_adj_matrix(vertices_info)
    ans = graph_bfs(v_init=1)
    for j in range(vertices_num):
        print(j + 1, ans[j + 1])

Solution (Python):



import sys
from collections import deque

UNVISITED, VISITED_IN_QUEUE, POPPED_OUT = 0, 1, 2


def generate_adj_matrix(v_info):
    for v_detail in v_info:
        v_adj_list = v_detail[2:]
        
        for each in v_adj_list:
            init_adj_matrix[int(v_detail[0]) - 1][int(each) - 1] = 1
    return init_adj_matrix


def graph_bfs(v_init):
    vertices_status_list[v_init] = VISITED_IN_QUEUE
    vertices_distance_list[v_init] = 0
    vertices_visit_queue.appendleft(v_init)

    while vertices_visit_queue:
        current_vertex = vertices_visit_queue.popleft()
        for v in range(1, vertices_num + 1):
            if adj_matrix[current_vertex - 1][v - 1] and vertices_status_list[v] is UNVISITED:
                vertices_status_list[v] = VISITED_IN_QUEUE
                vertices_distance_list[v] = vertices_distance_list[current_vertex] + 1
                vertices_visit_queue.append(v)
        vertices_status_list[current_vertex] = POPPED_OUT
    return vertices_distance_list


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices_num = int(_input[0])
    vertices_info = list(map(lambda x: x.split(), _input[1:]))
    init_adj_matrix = [[0] * vertices_num for _ in range(vertices_num)]
    

    
    vertices_visit_queue = deque()
    vertices_status_list = [UNVISITED] * vertices_num
    vertices_status_list.insert(0, -1)
    vertices_distance_list = [-1] * (vertices_num + 1)

    adj_matrix = generate_adj_matrix(vertices_info)
    ans = graph_bfs(v_init=1)
    for j in range(vertices_num):
        print(j + 1, ans[j + 1])

Solution (Python):



"""
input:
4
1 2 2 4
2 1 4
3 0
4 1 3

output:
1 0
2 1
3 2
4 1
"""

import sys
from collections import deque

UNVISITED, VISITED_IN_QUEUE, POPPED_OUT = 0, 1, 2


def generate_adj_matrix(v_info):
    for v_detail in v_info:
        v_index, adj_num, *adj_list = map(int, v_detail)
        
        init_adj_table[v_index].extend(adj_list)
    return init_adj_table


def graph_bfs(v_init):
    status[v_init] = VISITED_IN_QUEUE
    distance[v_init] = 0
    queue.appendleft(v_init)

    while queue:
        current = queue.popleft()
        for v in adj_table[current]:
            if status[v] is UNVISITED:
                status[v] = VISITED_IN_QUEUE
                distance[v] = distance[current] + 1
                queue.append(v)
        status[current] = POPPED_OUT
    return distance


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices_num = int(_input[0])
    vertices_info = list(map(lambda x: x.split(), _input[1:]))
    init_adj_table = [[] for _ in range(vertices_num + 1)]
    

    
    queue = deque()
    status = [UNVISITED] * (vertices_num + 1)
    distance = [-1] * (vertices_num + 1)

    adj_table = generate_adj_matrix(vertices_info)
    ans = graph_bfs(1)
    for j in range(vertices_num):
        print(j + 1, ans[j + 1])

Solution (Python):



"""
input:
4
1 2 2 4
2 1 4
3 0
4 1 3

output:
1 0
2 1
3 2
4 1
"""

import sys
from collections import deque

UNVISITED, VISITED_IN_QUEUE, POPPED_OUT = 0, 1, 2


def generate_adj_matrix(v_info):
    for v_detail in v_info:
        v_index, adj_num, *adj_list = map(int, v_detail)
        
        init_adj_table[v_index].extend(adj_list)
    return init_adj_table


def graph_bfs(v_init):
    status[v_init] = VISITED_IN_QUEUE
    distance[v_init] = 0
    queue.appendleft(v_init)

    while queue:
        current = queue.popleft()
        for v in adj_table[current]:
            if status[v] is UNVISITED:
                status[v] = VISITED_IN_QUEUE
                distance[v] = distance[current] + 1
                queue.append(v)
        status[current] = POPPED_OUT
    return distance


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices_num = int(_input[0])
    vertices_info = list(map(lambda x: x.split(), _input[1:]))
    init_adj_table = [[] for _ in range(vertices_num + 1)]
    

    
    queue = deque()
    status = [UNVISITED] * (vertices_num + 1)
    distance = [-1] * (vertices_num + 1)

    adj_table = generate_adj_matrix(vertices_info)
    ans = graph_bfs(1)
    for k, v in enumerate(ans[1:], 1):
        print(k, v)

Solution (Python):



"""
input:
4
1 2 2 4
2 1 4
3 0
4 1 3

output:
1 0
2 1
3 2
4 1
"""

import sys
from collections import deque

UNVISITED, VISITED_IN_QUEUE, POPPED_OUT = 0, 1, 2


def generate_adj_matrix(v_info):
    for v_detail in v_info:
        v_index, adj_num, *adj_list = map(int, v_detail)
        
        init_adj_table[v_index].extend(adj_list)
    return init_adj_table


def graph_bfs(v_init):
    status[v_init] = VISITED_IN_QUEUE
    distance[v_init] = 0
    queue.appendleft(v_init)

    while queue:
        current = queue.popleft()
        for v in adj_table[current]:
            if status[v] is UNVISITED:
                status[v] = VISITED_IN_QUEUE
                distance[v] = distance[current] + 1
                queue.append(v)
        status[current] = POPPED_OUT
    return distance


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices_num = int(_input[0])
    vertices_info = list(map(lambda x: x.split(), _input[1:]))
    init_adj_table = tuple([] for _ in range(vertices_num + 1))
    

    
    queue = deque()
    status = [UNVISITED] * (vertices_num + 1)
    distance = [-1] * (vertices_num + 1)

    adj_table = generate_adj_matrix(vertices_info)
    ans = graph_bfs(1)
    for k, v in enumerate(ans[1:], 1):
        print(k, v)

Solution (Python):
from collections import deque
from enum import Enum

class Bfs(object):
    """ Breadth First Search """
    class Status(Enum):
        """ ?????????????¨??????¶??? """
        white = 1  
        gray = 2  
        black = 3  

    def __init__(self, data):
        num_of_nodes = len(data)+1
        self.color = [Bfs.Status.white] * (num_of_nodes + 1)  
        self.Q = deque()  
        self.M = self._make_matrix(data)  
        self.D = [-1] * (len(data) + 1)  

    def _make_matrix(self, data):
        """ data(??£??\?????????)???????????£??\??????????????? (M[i][j]?????¢??§??????????????????+1??????????????????????????????) """
        num = len(data)
        graph_table = [[0] * (num+1) for _ in range(num+1)]
        for d in data:
            node_id = d[0]
            num_of_e = d[1]
            for e in d[2:]:
                graph_table[node_id][e] = 1
        return graph_table

    def search(self, start):
        """ start????????????????????????????????°??????????????? """
        self.Q.append(start)
        self.color[start] = Bfs.Status.gray
        self.D[start] = 0  

        while self.Q:
            u = self.Q.popleft()  
            edges = self.M[u]
            for i in range(1, len(edges)):
                if edges[i] == 1 and self.color[i] == Bfs.Status.white:
                    self.color[i] = Bfs.Status.gray
                    if self.D[i] == -1:
                        self.D[i] = self.D[u] + 1
                        self.Q.append(i)  


if __name__ == '__main__':
    
    num = int(input())
    data = []
    for _ in range(num):
        data.append(list(map(int, input().split(' '))))

    
    
    d = Bfs(data)
    d.search(1)

    
    for i in range(1, num+1):
        print('{0} {1}'.format(i, d.D[i]))

Solution (Python):

                
def BFS(i,A,d,dist):
    dist[i]=d
    for point in A[i]:
        if dist[point-1]==-1 or dist[point-1]>d+1:
            BFS(point-1,A,d+1,dist)

if __name__=="__main__":
    n=int(input())
    A=[]
    for i in range(n):
        A.append(list(map(int,input().split(" ")))[2:])
    dist=[-1]*n
    BFS(0,A,0,dist)

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

Solution (Python):



"""
input:
4
1 2 2 4
2 1 4
3 0
4 1 3

output:
1 0
2 1
3 2
4 1
"""

import sys
from collections import deque

UNVISITED, VISITED_IN_QUEUE, POPPED_OUT = 0, 1, 2


def graph_bfs(v_init):
    queue = deque()
    status[v_init] = VISITED_IN_QUEUE
    distance[v_init] = 0
    queue.appendleft(v_init)

    while queue:
        current = queue.popleft()
        for adj in adj_table[current]:
            if status[adj] is UNVISITED:
                status[adj] = VISITED_IN_QUEUE
                distance[adj] = distance[current] + 1
                queue.append(adj)
        status[current] = POPPED_OUT
    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    v_num = int(_input[0])
    vertices = list(map(lambda x: x.split(), _input[1:]))
    

    status = [UNVISITED] * (v_num + 1)
    distance = [-1] * (v_num + 1)

    adj_table = tuple([] for _ in range(v_num + 1))
    for v_info in vertices:
        v_index, adj_num, *adj_list = map(int, v_info)
        
        adj_table[v_index].extend(adj_list)

    graph_bfs(v_init=1)
    for index, v in enumerate(distance[1:], 1):
        print(index, v)

Solution (Python):



"""
input:
4
1 2 2 4
2 1 4
3 0
4 1 3

output:
1 0
2 1
3 2
4 1
"""

import sys
from collections import deque

UNVISITED, VISITED_IN_QUEUE, POPPED_OUT = 0, 1, 2


def graph_bfs(v_init):
    queue = deque()
    status[v_init] = VISITED_IN_QUEUE
    distance[v_init] = 0
    queue.appendleft(v_init)

    while queue:
        current = queue.popleft()
        for adj in adj_table[current]:
            if status[adj] is UNVISITED:
                status[adj] = VISITED_IN_QUEUE
                distance[adj] = distance[current] + 1
                queue.append(adj)
        status[current] = POPPED_OUT
    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    v_num = int(_input[0])
    vertices = list(map(lambda x: x.split(), _input[1:]))
    

    status = [UNVISITED] * (v_num + 1)
    distance = [-1] * (v_num + 1)

    adj_table = tuple([] for _ in range(v_num + 1))
    for v_info in vertices:
        v_index, adj_num, *adj_list = map(int, v_info)
        
        adj_table[v_index].extend(adj_list)

    graph_bfs(v_init=1)
    for index, v in enumerate(distance[1:], 1):
        print(index, v)

Solution (Python):



"""
input:
4
1 2 2 4
2 1 4
3 0
4 1 3

output:
1 0
2 1
3 2
4 1
"""

import sys
from collections import deque

UNVISITED, VISITED_IN_QUEUE, POPPED_OUT = 0, 1, 2


def graph_bfs(v_init):
    queue = deque()
    visited[v_init] = VISITED_IN_QUEUE
    distance[v_init] = 0
    queue.appendleft(v_init)

    while queue:
        current = queue.popleft()
        for adj in adj_table[current]:
            if visited[adj] is UNVISITED:
                visited[adj] = VISITED_IN_QUEUE
                distance[adj] = distance[current] + 1
                queue.append(adj)
        visited[current] = POPPED_OUT
    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    v_num = int(_input[0])
    vertices = map(lambda x: x.split(), _input[1:])

    visited = [UNVISITED] * (v_num + 1)
    distance = [-1] * (v_num + 1)

    adj_table = tuple([] for _ in range(v_num + 1))
    for v_info in vertices:
        v_index, adj_num, *adj_list = map(int, v_info)
        
        adj_table[v_index].extend(adj_list)

    graph_bfs(v_init=1)
    for index, v in enumerate(distance[1:], 1):
        print(index, v)

Solution (Python):
import sys

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def bfs(adj, nxt, dis, sumi, kyori):
    nnxt = []
    for u in nxt:
        sumi[u] = True
        dis[u] = kyori

    for u in nxt:
        for v in adj[u]:
            if not sumi[v]:
                nnxt.append(v)

    return nnxt, kyori + 1

def solve():
    n = int(input())
    adj = [None] * n
    for i in range(n):
        u, k, *vs = [int(j) - 1 for j in input().split()]
        adj[u] = vs

    

    sumi = [False] * n
    dis = [-1] * n
    nxt = [0]
    kyori = 0

    while nxt:
        nxt, kyori = bfs(adj, nxt, dis, sumi, kyori)

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

    pass

if __name__ == '__main__':
    solve()

Solution (Python):
import sys
from collections import deque

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def bfs(n, adj):
    dis = [-1] * n
    visited = [False] * n
    nxt = deque([0])
    dis[0] = 0
    visited[0] = True

    while nxt:
        u = nxt.popleft()

        for v in adj[u]:
            if not visited[v]:
                dis[v] = dis[u] + 1
                visited[v] = True
                nxt.append(v)

    return dis

def solve():
    n = int(input())
    adj = [None] * n
    for i in range(n):
        u, k, *vs = [int(j) - 1 for j in input().split()]
        adj[u] = vs

    
    dis = bfs(n, adj)

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

    pass

if __name__ == '__main__':
    solve()

Solution (Python):
from collections import deque


def bfs(root):
    Q = deque()
    distance[root] = 0
    Q.append(root)
    i = root
    while len(Q) > 0:
        i = Q.popleft()
        for v in range(n):
            if adjMat[i][v] == 1 and color[v] == 'white':
                Q.append(v)
                color[v] = 'gray'
                distance[v] = distance[i] + 1
        color[i] = 'black'


n = int(input())
adjMat = [[0] * n for _ in range(n)]
color = ['white'] * n
distance = [-1] * n

for _ in range(n):
    adj = list(map(int, input().split()))
    i = adj[0]
    v = adj[2:]
    for j in v:
        adjMat[i - 1][j - 1] = 1

bfs(0)

for i in range(n):
    out = ''
    out += '{} {}'.format(i + 1, distance[i])
    print(out)

Solution (Python):


import sys
import os
import math


N = int(input())

E = []
E.append([])
d = [-1] * (N + 1)

for i in range(N):
    lst = list(map(int, input().split()))
    nodes = lst[2:]
    E.append(nodes)


q = []
q.append(1)

visited = [False] * (N + 1)
d[1] = 0
visited[1] = True

while q:
    index = q.pop(0)

    
    for v in E[index]:
        if not visited[v]:
            q.append(v)
            d[v] = d[index] + 1
            visited[v] = True


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

Solution (Python):
import sys
from collections import deque

inf = 1<<30

def solve():
    n = int(input())
    Adj = [None] * n

    for i in range(n):
        u, k, *line = [int(i) - 1 for i in input().split()]
        Adj[u] = line

    d = bfs(n, Adj)

    for i, di in enumerate(d, start=1):
        if di == inf:
            print(i, -1)
        else:
            print(i, di)

def bfs(n, Adj):
    d = [inf] * n
    d[0] = 0
    nxts = deque([0])

    while nxts:
        u = nxts.popleft()

        for v in Adj[u]:
            if d[v] == inf:
                d[v] = d[u] + 1
                nxts.append(v)

    return d

if __name__ == '__main__':
    solve()

Solution (Python):
def breadth_first_search(G):
  n = len(G)
  d = [-1] * (n + 1)
  d[1] = 0
  queue = [1]

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

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

G = {}
for i in range(int(input())):
  x = list(map(int, input().split()))
  G[x[0]] = x[2:]

breadth_first_search(G)

Solution (Python):
n = int(input())
Adj = [[0 for i in range(n)] for i in range(n)]
 
for i in range(n):
    u = list(map(int, input().split()))
    if u[1] > 0:
        for i in u[2: 2 + u[1]]:
            Adj[u[0] - 1][i - 1] = 1
 
color = [0] * n
d = [-1] * n
import queue
Q = queue.Queue()

color[0] = 1
d[0] = 0
Q.put(1)
while not Q.empty():
    u = Q.get()
    for v in range(1, n+1):
        if Adj[u-1][v-1] == 1 and color[v-1] == 0:
            color[v-1] = 1
            d[v-1] = d[u-1] + 1
            Q.put(v)
    color[u-1] = 2

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

Solution (Python):
def bfs(G, s):
    d = {key: -1 for key in G.keys()}
    d[s] = 0
    Q = [s]
    while len(Q) > 0:
        u = Q.pop(0)
        for v in G[u]:
            if d[v] < 0:
                d[v] = d[u] + 1
                Q.append(v)

    return d


if __name__ == '__main__':
    G = {}
    n = int(input())
    for _ in range(n):
        tmp = list(map(int, input().split()))
        u = tmp.pop(0)
        k = tmp.pop(0)
        G[u] = tmp
    d = bfs(G, 1)
    for node in G:
        print('{0} {1}'.format(node, d[node]))

Solution (Python):
n=int(input())
G=[[0,[],0,-1]]
for i in range(n):
    v=[int(j) for j in input().split(" ")]
    u=v.pop(0)
    k=v.pop(0)
    G.append([k,v,0,-1])





distance=0
dis_list=[1]
G[1][3]=0
G[1][2]=1
while len(dis_list)!=0:
    distance+=1
    dis_list_cash=[]
    for i in dis_list:
        k=G[i][0]
        v=G[i][1]
        for j in range(k):
            if G[v[j]][2]==0:
                G[v[j]][2]=1
                G[v[j]][3]=distance
                dis_list_cash.append(v[j])
    
    dis_list=dis_list_cash



for i in range(1,n+1):
    print(str(i)+" "+str(G[i][3]))

Solution (Python):


def BFS(adj, start):
    n = len(adj)
    d = [n] * n
    flag = [0] * n
    Q = []

    Q.append(start)
    d[start] = 0

    while len(Q) != 0:
        u = Q.pop(0)
        v = [i for i, x in enumerate(adj[u]) if (x == 1) and (flag[i] == 0)] 
        
        for i in v:
            Q.append(i)
            d[i] = min(d[u] + 1, d[i])
            flag[u] = 1
    
    for i in range(n):
        if d[i] == n:
            d[i] = -1

    return d

def main():
    n = int(input())
    adj = [[0 for i in range(n)] for j in range(n)]
    
    for i in range(n):
        tmp = list(map(int, input().split()))
        u = tmp[0]
        u = u -1
        k = tmp[1]
        v = tmp[2:]
        for j in range(k):
            adj[u][v[j]-1] = 1
    
    d = BFS(adj, 0)
    for i in range(n):
        print(i+1, d[i])


if __name__ == "__main__":
    main()