Problem:


  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

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.



Sample input:
4
1 2 2 4
2 1 4
3 0
4 1 3


Sample output:
1 0
2 1
3 2
4 1

Submission status: Accepted

Solution code:
from sys import stdin
from collections import deque

def read_graph(n):
    A = [ [0]*(n+1) for _ in range(n+1) ]
    for _ in range(n):
        line = deque(stdin.readline().strip().split())
        i = line.popleft()
        line.popleft()
        for k in line:
            A[int(i)][int(k)] = 1
    return A

def bfs_ctrl(n, A):
    color = ["WHITE"] * (n+1)
    d = [-1] * (n+1)
    Q = deque([])

    def bfs(s):
        nonlocal color
        nonlocal d
        nonlocal Q
        color[s] = "GRAY"
        d[s] = 0
        Q.append(s)

        while Q:
            u = Q.popleft()
            for v in range(1, n+1):
                if A[u][v] and color[v] == "WHITE":
                    color[v] = "GRAY"
                    d[v] = d[u] + 1
                    Q.append(v)

            color[u] = "BLACK"

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

n = int(input())
A = read_graph(n)
bfs_ctrl(n, A)

Submission status: Accepted

Solution code:
from sys import maxsize


def read_adj():
    n = int(input())
    adj_list = [[] for _ in range(n + 1)]
    for _ in range(1, n + 1):
        u, _, *adj = [int(x) for x in input().split()]
        adj_list[u] = adj
    return n, adj_list


def shortest_paths(n, adj_list, ini_key):
    dist = [maxsize] * (n + 1)

    S = [ini_key]
    dist[ini_key] = 0

    while S != []:
        key = S.pop()
        d = dist[key] + 1
        for k in adj_list[key]:
            if d < dist[k]:
                dist[k] = d
                S.append(k)

    return dist


def print_dist(n, dist):
    for i in range(1, n + 1):
        if dist[i] == maxsize:
            print(i, -1)
        else:
            print(i, dist[i])


def main():
    n, adj_list = read_adj()
    dist = shortest_paths(n, adj_list, 1)
    print_dist(n, dist)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())                #エッジの個数
edge = [[] for _ in range(n)]   #エッジの隣接リスト（お隣さんを格納する）

for _ in range(n):
  u, _, *v = map(lambda x: int(x)-1, input().split())
  edge[u] = sorted(v)           #入力された隣接頂点をお隣さんリストに格納

dist = [-1] * n                #始点から各頂点iまでの距離を測るリスト
dist[0] = 0                    #0番目のエッジの距離
Q = deque([0])                 #次に訪問すべきエッジを記録するキュー

while len(Q):
  v = Q.popleft()             #vに次に訪問するエッジを代入（v=自分）
  for c in edge[v]:           #v(自分)のお隣さんの数分だけイテレーション
    if dist[c] == -1:         #もしお隣さんお距離が-1になっていたら
      dist[c] = dist[v] + 1   #お隣さんの距離=自分の距離+1にする
      Q.append(c)             #次に訪問すべきキューにお隣さんを代入

for i, d in enumerate(dist):
  print(i+1, d)

Submission status: Accepted

Solution code:
import heapq
from collections import deque
from enum import Enum
import sys
import math
from _heapq import heappush, heappop

BIG_NUM = 2000000000
MOD = 1000000007
EPS = 0.000000001

class Info:
    def __init__(self,arg_node_id,arg_sum_cost):
        self.node_id = arg_node_id
        self.sum_cost = arg_sum_cost


V = int(input())
ADJ = [[] for i in range(V)]

for loop in range(V):
    input_str = list(map(int,input().split()))
    node_id = input_str[0]-1
    for i in range(input_str[1]):
        ADJ[node_id].append(input_str[2+i]-1)

visited = [False]*V
visited[0] = True

min_dist = [-1]*V
min_dist[0] = 0

Q = deque()
Q.append((Info(0,0)))

while len(Q) > 0:
    info = Q.popleft()
    for next_node in ADJ[info.node_id]:
        if visited[next_node] == True:
            continue
        visited[next_node] = True
        min_dist[next_node] = info.sum_cost+1
        Q.append((Info(next_node,min_dist[next_node])))

for i in range(V):
    print("%d %d"%(i+1,min_dist[i]))

Submission status: Accepted

Solution code:
from queue import *

class Vertex:
	def __init__(self, u, k):
		self.u = u
		self.vertices = [0] * k
		self.d = -1
	def __str__(self):
		return str(self.u) + ' ' + str(self.d)

class Inf:
	def __init__(self,u,d):
		self.u = u
		self.d = d

def BFS(n, vertices):
	q = Queue()
	q.put(Inf(1,0))
	while q.empty() == False:
		inf = q.get()
		vertex = vertices[inf.u-1]
		if vertex.d == -1:
			vertex.d = inf.d
		else:
			vertex.d = min(vertex.d, inf.d)
		dist = inf.d + 1
		for i in range(len(vertex.vertices)):
			u = vertex.vertices[i]
			if vertices[u-1].d == -1:
				q.put(Inf(u, dist))
	
n = int(input())
vertices = []
for i in range(n):
	v = list(map(int, input().split()))
	u = v[0]
	k = v[1]
	vertex = Vertex(u, k)
	for j in range(k):
		vertex.vertices[j] = v[j+2]
	vertices.append(vertex)

BFS(n, vertices)
for i in range(n):
	print(str(vertices[i]))

Submission status: Accepted

Solution code:
from collections import deque

def bfs(s, n, m):
    q = deque()
    q.append(s)
    INFTY = 1 << 21
    d = [INFTY] * n
    d[s] = 0
    while len(q) != 0:
        u = q[0]
        q.popleft()
        for v in range(n):
            if not m[u][v]:
                continue
            if d[v] != INFTY:
                continue
            d[v] = d[u] + 1
            q.append(v)
    for i in range(n):
        result = str(i+1)
        if d[i] == INFTY:
            result += ' -1'
        else:
            result += ' %d' % d[i]
        print(result)


n = int(input())
m = [[False] * n for i in range(n)]
for i in range(n):
    line = [int(v) for v in input().split()]
    u = line[0] - 1
    for v in line[2:]:
        v -= 1
        m[u][v] = True

bfs(0, n, m)

Submission status: Accepted

Solution code:
# Graph I - Breadth First Search
from collections import deque
def bfs(A,d):
    dq = deque()
    dq.append(0)
    d[0] = 0
    while len(dq):
        v = dq.pop()
        for i in range(len(A[v])-1,-1,-1):
            f = A[v][i]
            if f == 1 and d[i] == -1:
                d[i] = d[v] + 1
                dq.appendleft(i)

n = int(input())
A = []
for _ in range(n):
    ss = list(map(int, input().split()))
    u = ss[0] - 1
    row = [0 for _ in range(n)]
    for i in range(ss[1]):
        idx = 2 + i
        row[ss[idx]-1] = 1
    A.append(row)

d = [-1 for _ in range(n)]
bfs(A,d)

for i,t in enumerate(d): print(i+1,t)

Submission status: Accepted

Solution code:
n=int(input())
G=[[] for i in range(n)]
#G=[]
Q=[1]
d=[-1]*n
d[0]=0
visited=[False]*n
visited[0]=True

for i in range(n):
    arr=[int(x) for x in input().split()[2:]]
    for l in arr:
        G[i].append(l)
        #G[l-1].append(i+1)
    

kyori=0
while len(Q)!=0:
    
    #print(Q)
    #print(visited)
    v=Q.pop(0)
    
    for j in G[v-1]:
        if visited[j-1]:#次に行くところがすでに踏破済みだったら
            continue#更新しない
        else:
            d[j-1]=d[v-1]+1
            Q.append(j)
            visited[j-1]=True
for a in range(n):
    print(a+1,d[a])

Submission status: Runtime Error

Solution code:
def f(v,c):
    check[v]=c
    c+=1
    for i in edge[v]:
        if check==-1:
            c=f(i,c)
    time[v]=c
    c+=1
    return c

n=int(input())
edge=[[]for in range(n)]
for i in range(n):
    a=list(map(int,input().split())
           edge[a[0]]=sorted(a[2:])
time=[-1]*n
check=[-1]*n
c=1
for i in range(n):
     if check[i]==-1:
               c=f(i, c)
           for i,(ch, t) in enumerate(zip(check,time)):
               print(i+1, ch, t)

Submission status: Runtime Error

Solution code:
def get_depth(graph,tmp_depth,vertex_list,depth_list):
    new_vertex_list=[]
    for vertex in vertex_list:
        for j in range(len(depth_list)):
            if(graph[vertex][j]!=0 and depth_list[j]==-1):
                depth_list[j]=tmp_depth + 1
                new_vertex_list.append(j)
    get_depth(graph,tmp_depth+1,new_vertex_list,depth_list)


#グラフの作成
n=int(input())
graph=[[0]*n for loop in range(n)]
for loop in range(n):
    tmp_ope=list(map(int,input().split()))
    for j in range(tmp_ope[1]):
        graph[tmp_ope[0]-1][tmp_ope[j+2]-1]=1


depth_list=[-1]*n
depth_list[0]=0
vertex_list=[0]
get_depth(graph,0,vertex_list,depth_list)

for i in range(n):
    print(f"{i+1} {depth_list[i]}")

Submission status: Runtime Error

Solution code:
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]))

Submission status: Runtime Error

Solution code:
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 range(n):
    if L[i] == 0:
        L[i] == -1

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

Submission status: Runtime Error

Solution code:
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 range(n):
    if L[i] == 0:
        L[i] == -1

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

Submission status: Runtime Error

Solution code:
N= int(input())
E = [input().split()[2:] for _ in [0]*N]
Q = [0]
L = [0] + [-1]*N
def func(ide):
    for i in E[ide]:
        i = int(i) - 1
        if L[i] < 0 :L[i] = L[ide] +1 ;Q += [i]


while Q:top = Q.pop();func(top)

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

Submission status: Runtime Error

Solution code:
N= int(input())
E = [input().split()[2:] for _ in [0]*N]
Q = [0]
L = [0] + [-1]*N
def func(ide):
    for i in E[ide]:
        i = int(i) - 1
        if L[i] < 0 :L[i] = L[ide] +1 ; Q+= [i]


while Q:top = Q.pop(0);func(top)

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

Submission status: Runtime Error

Solution code:
N= int(input())
E = [input().split()[2:] for _ in range(N)]
Q = [0]
L = [0] + [-1]*N
flag = [1] + [0]*N
def func(ide):
    global Q
    for i in E[ide]:
        i = int(i) - 1
        if frag[i] != 1:frag[i] = 1;L[i] = L[ide] +1 ;Q.append(i)
    

while Q:top = Q.pop(0);func(top)

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

Submission status: Runtime Error

Solution code:
N= int(input())
E = [input().split()[2:] for _ in range(N)]
Q = [0]
L = [0] + [-1]*N
frag = [1] + [0]*N
def func(ide):
    global Q
    for i in E[ide]:
        i = int(i) - 1
        if frag[i] != 1:frag[i] = 1;L[i] = L[ide] +1 ;Q.append(i)
        return else
    

while Q:top = Q[0];func(top);del Q[0]

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

Submission status: Runtime Error

Solution code:
import numpy as np
N= int(input())
frag, T, L, Q = np.zeros(N),np.zeros(N),np.zeros(N),[0]
# frag, T, L,Q = [0]*N, [0]*N, [0]*N, [0]
a = 100
frag[0] = 1
def func(ide):
#     print("frag = {}".format(frag))
    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 None
            


E = [input().split()[2:] for _ in range(N)]

while Q:
    top = Q[0]
    func(top)
    del Q[0]
for i in range(N):print(i + 1 ,int(L[i]))

Submission status: Runtime Error

Solution code:
#!/usr/bin/python3

def find(id, V, d, dist):
    i = id - 1
    dist[i] = d
    for v in V[i]:
        find(v, V, d + 1, dist)
    
n = int(input())
# [isFind, d, f]
A = [[False, 0, 0] for i in range(n)]
U = []
V = []
dist = [-1] * n
for i in range(n):
    l = list(map(int, input().split()))
    U.append(l[0])
    V.append(l[2:])

find(1, V, 0, dist)

for u in U:
    print(u, dist[u - 1])

Submission status: Runtime Error

Solution code:
def BFS(s, r):
    d[s] = r
    for i in range(1, n+1):
        if G[s][i] == 1 and flag[i] == 0:
            BFS(i, r+1)

n = int(raw_input())
G = [[0 for i in range(n+1)] for j in range(n+1)]
d = [-1 for i in range(n+1)]

for i in range(n):
    v = map(int, raw_input().split())
    for j in range(v[1]):
        G[v[0]][v[2+j]] = 1

flag = [0 for i in range(n+1)]
BFS(1, 0)

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

Submission status: Runtime Error

Solution code:
class node:
    def __init__(self, num):
        self.number     = num
        self.distance   = -1
        self.link_node  = []
        self.is_serched = False

def BFS(node):
    for item in node.link_node:
        if item.is_serched == False:
            item.distance = node.distance + 1
            item.is_serched = True
    for item in node.link_node:
        BFS(item)
n = input()
node_list = [None] * (n + 1)

for i in xrange(1, n + 1):
    node_list[i] = node(i)

for i in xrange(1, n + 1):
    line = raw_input().split()
    for node_num in line[2 : ]:
        node_list[i].link_node.append(node_list[int(node_num)])

node_list[1].is_serched = True
node_list[1].distance = 0
BFS(node_list[1])

for item in node_list[1 : ]:
    print '%s %s' % (str(item.number), str(item.distance))

Submission status: Runtime Error

Solution code:
class node:
    def __init__(self, num):
        self.number     = num
        self.distance   = -1
        self.link_node  = []
        self.is_serched = False

class queue:
    def __init__(self):
        self.top = 0
        self.bottom = 0
        self.que = [None] * 100
    
    def dequeue(self):
        self.top = self.top + 1
        return self.que[self.top - 1]
    
    def enqueue(self, item):
        self.que[self.bottom] = item
        self.bottom = self.bottom + 1
    
    def is_empty(self):
        if self.top == self.bottom:
            return True
        else:
            return False

n = input()
node_list = [None] * (n + 1)

for i in xrange(1, n + 1):
    node_list[i] = node(i)

for i in xrange(1, n + 1):
    line = raw_input().split()
    for node_num in line[2 : ]:
        node_list[i].link_node.append(node_list[int(node_num)])

node_que = queue()

node_list[1].distance = 0
node_que.enqueue(node_list[1])
while node_que.is_empty() == False:
    top_item = node_que.que[node_que.top]
    top_item.is_serched = True
    for item in top_item.link_node:
        if item.is_serched == False:
            node_que.enqueue(item)
            if item.distance == -1:
                item.distance = top_item.distance + 1
            elif item.distance > top_item.distance + 1:
                item.distance = top_item.distance + 1
    node_que.dequeue()

for item in node_list[1 : ]:
    print '%s %s' % (str(item.number), str(item.distance))

Submission status: Runtime Error

Solution code:
class node:
    def __init__(self, num):
        self.number     = num
        self.distance   = -1
        self.link_node  = []
        self.is_serched = False

class queue:
    def __init__(self):
        self.top = 0
        self.bottom = 0
        self.que = [None] * 1000
    
    def dequeue(self):
        self.top = self.top + 1
        return self.que[self.top - 1]
    
    def enqueue(self, item):
        self.que[self.bottom] = item
        self.bottom = self.bottom + 1
    
    def is_empty(self):
        if self.top == self.bottom:
            return True
        else:
            return False

n = input()
node_list = [None] * (n + 1)

for i in xrange(1, n + 1):
    node_list[i] = node(i)

for i in xrange(1, n + 1):
    line = raw_input().split()
    for node_num in line[2 : ]:
        node_list[i].link_node.append(node_list[int(node_num)])

node_que = queue()

node_list[1].distance = 0
node_que.enqueue(node_list[1])
while node_que.is_empty() == False:
    top_item = node_que.que[node_que.top]
    top_item.is_serched = True
    for item in top_item.link_node:
        if item.is_serched == False:
            node_que.enqueue(item)
            if item.distance == -1:
                item.distance = top_item.distance + 1
            elif item.distance > top_item.distance + 1:
                item.distance = top_item.distance + 1
    node_que.dequeue()

for item in node_list[1 : ]:
    print '%s %s' % (str(item.number), str(item.distance))

Submission status: Runtime Error

Solution code:
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)]
g = [0 for i in range(n)]
temp_d = [0]

def BFS_visit(s, temp_d):
    if temp_d == 99999:
        temp_d = 0
    if d[s] > temp_d:
        d[s] = temp_d
    temp_d += 1
    for e in range(n):
        if M[s][e] == 1:
            BFS_visit(e, temp_d)

def BFS():
    for s in range(n):
        BFS_visit(s, d[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])

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
    g[i] = G[1]
BFS()

Submission status: Runtime Error

Solution code:

def BFS(s = 0, time = 0):
    d[s] = time
    if len(Q) != 0:
        Q.pop(0)
        color[s] = 2
    for j in range(len(d)):
        if A[i][j] == 1 and color[j] == 0:
            Q.append(A[i][j])
            color[j] = 1
    for j in range(Q):
        time = time + 1
        BFS(Q[j], time)

n = int(raw_input())
A = [0] * n
for i in range(n):
    A[i] = [0] * n

for i in range(n):
    value = map(int, raw_input().split())
    u = value[0] - 1
    k = value[1]
    nodes = value[2:]
    for j in range(k):
        v = nodes[j] - 1
        A[u][v] = 1

color = [0] * n
Q = [0]
d = [-1] * n

BFS(0, 0)

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

Submission status: Runtime Error

Solution code:
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)]
g = [0 for i in range(n)]
temp_d = [0]

def BFS_visit(s, temp_d):
    if temp_d == 99999:
        temp_d = 0
    if d[s] > temp_d:
        d[s] = temp_d
    temp_d += 1
    for e in range(n):
        if M[s][e] == 1 and s != e:
            BFS_visit(e, temp_d)

def BFS():
    s = 0
    BFS_visit(0, d[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])

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
    g[i] = G[1]
BFS()

Submission status: Runtime Error

Solution code:
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)]
g = [0 for i in range(n)]
temp_d = [0]

def BFS_visit(s, temp_d):
    if temp_d == 99999:
        temp_d = 0
    if d[s] > temp_d:
        d[s] = temp_d
    temp_d += 1
    for e in range(1, n):
        if M[s][e] == 1 and s != e:
            BFS_visit(e, temp_d)

def BFS():
    s = 0
    BFS_visit(0, d[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])

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
    g[i] = G[1]
BFS()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
from _future_ import division, print_function
from sys import stdin
from Quene import Quene

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

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin
from Quene import Quene

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

Submission status: Runtime Error

Solution code:
n = int(raw_input())

G = [0 for i in range(n)] 
a = [[0 for i in range(n)] for j in range(n)]
st = [0 for i in range(n)]
dis = [0]
b = [0 for i in range(n)]

def bfs_visit(s):
    st[s] = 1
    dis[0] = 0
    for k in range(n):
      if a[s][k] == 1 and st[k] == 0:
         dis[0] += 1
         b[k] = dis[0]
         bfs_visit[k]

def main():
    s = 1
    b[1] = 0
    bfs_visit(s)
    for s in range(n):
       if i!=1 and b[i] == 0:
           b[i] = -1
    for s in range(n):
       print (s+1,b[s])

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

Submission status: Runtime Error

Solution code:
n = int(raw_input())

G = [0 for i in range(n)] 
a = [[0 for i in range(n)] for j in range(n)]
dis = [-1 for i in range(n)]

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

def bfs_visit(s):
    for k in range(n):
      if a[s][k] == 1 and dis[k] == -1:
         dis[k] = dis[s] + 1
         bfs_visit(k)

for s in range(s):
    bfs_visit()
for s in range(s):
    print (s+1,dis[s])

Submission status: Runtime Error

Solution code:
n = int(raw_input())

G = [0 for i in range(n)] 
a = [[0 for i in range(n)] for j in range(n)]
dis = [-1 for i in range(n)]
dis[0] = 0

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

def bfs_visit(s):
    for k in range(n):
      if a[s][k] == 1 and dis[k] == -1:
         dis[k] = dis[s] + 1
         bfs_visit(k)

for s in range(s):
    bfs_visit()
for s in range(s):
    print (s+1,dis[s])

Submission status: Runtime Error

Solution code:
n = int(raw_input())
 
G = [0 for i in range(n)] 
a = [[0 for i in range(n)] for j in range(n)]
dis = [-1 for i in range(n)]
dis[0] = 0
 
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
 
def bfs_visit(s):
    for k in range(n):
      if a[s][k] == 1 and dis[k] == -1:
         dis[k] = dis[s] + 1
         bfs_visit(k)

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

Submission status: Runtime Error

Solution code:
n = int(raw_input())
 
G = [0 for i in range(n)] 
a = [[0 for i in range(n)] for j in range(n)]
dis = [1000 for i in range(n)]
dis[0] = 0

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

Submission status: Runtime Error

Solution code:
n = int(raw_input()) 
G = [0 for i in range(n)] 
a = [[0 for i in range(n)] for j in range(n)]
dis = [1000 for i in range(n)]
dis[0] = 0
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
 
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 s in range(n):
    bfs_visit(s)
for s in range(n):
    if dis[s] == 1000:
       dis[s] = -1
for s in range(n):
    print'{0} {1}'.format(s+1, d[s])

Submission status: Runtime Error

Solution code:
n = int(raw_input()) 
G = [0 for i in range(n)] 
a = [[0 for i in range(n)] for j in range(n)]
dis = [10000 for i in range(n)]
dis[0] = 0

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

Submission status: Runtime Error

Solution code:
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)]
dis[0] = 0


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
 

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

Submission status: Runtime Error

Solution code:
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])

Submission status: Runtime Error

Solution code:
nn = int(raw_input())
   
dis = [99999 for i in range(n)]
G = [0 for i in range(n)]
v = [[0 for i in range(n)] for j in range(n)]
   
def BFS(s):
  for e in range(n):
    if v[s][e] == 1:
      if dis[e] > dis[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]):
    v[G[0]-1][G[2+j]-1] = 1
   
dis[0] = 0
for s in range(n):
  BFS(s)
for s in range(n):
  if dis[s] == 99999:
    dis[s] = -1
for s in range(n):
  print'{0} {1}'.format(s+1, dis[s])

Submission status: Runtime Error

Solution code:
n = int(raw_input())
   
dis = [99999 for i in range(n)]
G = [0 for i in range(n)]
v = [[0 for i in range(n)] for j in range(n)]
   
def BFS(s):
  for e in range(n):
    if v[s][e] == 1:
      if dis[e] > dis[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]):
    v[G[0]-1][G[2+j]-1] = 1
   
dis[0] = 0
for s in range(n):
  BFS(s)
for s in range(n):
  if dis[s] == 99999:
    dis[s] = -1
for s in range(n):
  print'{0} {1}'.format(s+1, dis[s])

Submission status: Runtime Error

Solution code:


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

 
Compile Error Logs: 

You are not authorized to see the message.

Submission status: Runtime Error

Solution code:
n = input()

d = [1000 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]

def BFS(s):
  q = []
  q.append(s)
  d[s] = 0
  while q.length != 0:
    u = q.pop()
    for v in range(n):
      if M[u][v] == 0 and d[v] != 1000:
        d[v] = d[u] + 1
        q.push(v)
  for i in range(n):
    print i+1, d[i]

for i in range(n):
  G = map(int, raw_input().split())
  for j in range(X[1]):
    M[G[0]-1][G[2+j]-1] = 1

BFS()

Submission status: Runtime Error

Solution code:
n = input()

d = [1000 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]

def BFS(s):
  q = []
  q.append(s)
  d[s] = 0
  while q.length != 0:
    u = q.pop()
    for v in range(n):
      if M[u][v] == 0 and d[v] != 1000:
        d[v] = d[u] + 1
        q.push(v)
  for i in range(n):
    print i+1, d[i]

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

BFS()

Submission status: Runtime Error

Solution code:
n = input()

d = [1000 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]

def BFS(s):
  q = []
  q.append(s)
  d[s] = 0
  while q.length != 0:
    u = q.pop()
    for v in range(n):
      if M[u][v] == 0 and d[v] != 1000:
        d[v] = d[u] + 1
        q.push(v)
  for i in range(n):
    print i+1, d[i]

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

BFS(0)

Submission status: Runtime Error

Solution code:
n = input()

d = [1000 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]

def BFS(s):
  q = []
  q.append(s)
  d[s] = 0
  while q.length != 0:
    u = q.pop(0)
    for v in range(n):
      if M[u][v] == 0 and d[v] != 1000:
        d[v] = d[u] + 1
        q.append(v)
  for i in range(n):
    print i+1, d[i]

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

BFS(0)

Submission status: Runtime Error

Solution code:
n = input()
 
d = [1000 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]
 
def BFS(s):
  q = []
  q.append(s)
  d[s] = 0
  while q.length != 0:
    u = q[0]
    q.pop(0)
    for v in range(n):
      if M[u][v] == 0 and d[v] != 1000:
        d[v] = d[u] + 1
        q.append(v)
  for i in range(n):
    print i+1, d[i]
 
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
 
BFS(0)