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: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Jul  8 10:56:33 2018

@author: maezawa
"""
n = int(input())
adj = [[] for _ in range(n)]
d = [-1 for _ in range(n)]
d[0] = 0


for j in range(n):
    ain = list(map(int, input().split()))
    u = ain[0]
    k = ain[1]
    for i in range(k):
        adj[u-1].append(ain[i+2]-1)
    adj[u-1].sort()
    #print(*adj[u-1])

stack = [0]

while stack:
    print(stack)
    current = stack[-1]
    flag = 0
    for k in adj[current]:
        if d[k] <= 0:
            d[k] = d[current]+1
            stack.append(k)
            flag = 1
    if flag == 0:
        stack.pop()

    #print('current = {}, t = {}'.format(current, t))
    #print('stack', *stack)

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

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Jul  8 10:56:33 2018

@author: maezawa
"""
n = int(input())
adj = [[] for _ in range(n)]
d = [-1 for _ in range(n)]
d[0] = 0


for j in range(n):
    ain = list(map(int, input().split()))
    u = ain[0]
    k = ain[1]
    for i in range(k):
        adj[u-1].append(ain[i+2]-1)
    adj[u-1].sort()
    #print(*adj[u-1])

stack = [0]

while stack:
    #print(stack)
    current = stack[-1]
    flag = 0
    for k in adj[current]:
        if d[k] <= 0:
            d[k] = d[current]+1
            stack.append(k)
            flag = 1
    if flag == 0:
        stack.pop()

    #print('current = {}, t = {}'.format(current, t))
    #print('stack', *stack)

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

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Jul  8 10:56:33 2018

@author: maezawa
"""
n = int(input())
adj = [[] for _ in range(n)]
d = [-1 for _ in range(n)]
d[0] = 0


for j in range(n):
    ain = list(map(int, input().split()))
    u = ain[0]
    k = ain[1]
    for i in range(k):
        adj[u-1].append(ain[i+2]-1)
    adj[u-1].sort()
    #print(*adj[u-1])

stack = [0]

while stack:
    print(stack)
    current = stack[-1]
    flag = 0
    for k in adj[current]:
        if d[k] < 0:
            d[k] = d[current]+1
            stack.append(k)
            flag = 1
        elif d[k] > d[current]+1:
            d[k] = d[current]+1
    if flag == 0:
        stack.pop()

    #print('current = {}, t = {}'.format(current, t))
    #print('stack', *stack)

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

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Jul  8 10:56:33 2018

@author: maezawa
"""
n = int(input())
adj = [[] for _ in range(n)]
d = [-1 for _ in range(n)]
d[0] = 0


for j in range(n):
    ain = list(map(int, input().split()))
    u = ain[0]
    k = ain[1]
    for i in range(k):
        adj[u-1].append(ain[i+2]-1)
    adj[u-1].sort()
    #print(*adj[u-1])

stack = [0]

while stack:
    #print(stack)
    current = stack[-1]
    flag = 0
    for k in adj[current]:
        if d[k] < 0:
            d[k] = d[current]+1
            stack.append(k)
            flag = 1
        elif d[k] > d[current]+1:
            d[k] = d[current]+1
    if flag == 0:
        stack.pop()

    #print('current = {}, t = {}'.format(current, t))
    #print('stack', *stack)

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

Submission status: Wrong Answer

Solution code:
n = int(input())
a = [101] * n
a[0] = 0
for i in range(n):
    t = list(map(int, input().split()))
    del t[1]
    if len(t) >= 2:
        for j in range(1, len(t)):
            a[t[j] - 1] = min(a[t[j] - 1], a[t[0] - 1] + 1)
for i in range(n):
    if a[i] == 101:
        print("{} {}".format(i + 1, -1))
    else:
        print("{} {}".format(i + 1, a[i]))

Submission status: Wrong Answer

Solution code:
n = int(input())
graph = [[0 for i in range(n)] for j in range(n)]
d = [0] * n
f = [0] * n
queue = [0]


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

while len(queue) != 0:
    i = queue.pop(0)
    for j in range(n):
        if (graph[i][j] == 1) & (f[j] == 0):
            queue.append(j)
            f[j] = 1
            d[j] = d[i] + 1

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

Submission status: Wrong Answer

Solution code:
n = int(input())
graph = [[0 for i in range(n)] for j in range(n)]
d = [0] * n
f = [0] * n
queue = [0]


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

while len(queue) != 0:
    i = queue.pop(0)
    for j in range(n):
        if (graph[i][j] == 1) & (f[j] == 0):
            queue.append(j)
            f[j] = 1
            d[j] = d[i] + 1

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

Submission status: Wrong Answer

Solution code:
n = int(input())
graph = [[0 for i in range(n)] for j in range(n)]
d = [0] * n
f = [0] * n
queue = [0]


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

while len(queue) != 0:
    i = queue.pop(0)
    for j in range(i, n):
        if (graph[i][j] == 1) & (f[j] == 0):
            queue.append(j)
            f[j] = 1
            d[j] = d[i] + 1

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

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
A = [0]*(n+1)
D = [0]*(n+1)
DP = [0]*(n+1)
d = deque()
for i in range(n):
    A[i+1] = [int(i) for i in input().split()]
d.append(1)
DP[1]=0
while(len(d)>0):
    tmp = d.pop()
    for i in A[tmp][2:]:
        if not DP[i]:
            D[i] = D[tmp]+1
            DP[i] = 1
            d.appendleft(i)
for i in range(1,n+1):
    tmp = "{} {}".format(i,D[i])
    print(tmp)

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
A = [0]*(n+1)
D = [-1]*(n+1)
DP = [0]*(n+1)
d = deque()
for i in range(n):
    A[i+1] = [int(i) for i in input().split()]
d.append(1)
D[1] = 0
DP[1] = 0
while(len(d)>0):
    tmp = d.pop()
    for i in A[tmp][2:]:
        if not DP[i]:
            D[i] = D[tmp]+1
            DP[i] = 1
            d.appendleft(i)
for i in range(1,n+1):
    tmp = "{} {}".format(i,D[i])
    print(tmp)

Submission status: Wrong Answer

Solution code:
#coding: utf-8
inf = 100000000
n = int(input())

List = [0] + [list(map(int,input().split())) for i in range(n)]
color = [0] + ["white" for  i in range(n)]
d = [inf for i in range(n+1)]

s = 1
Q = [s]
d[s] = 0
while Q != []:
    q = Q.pop()
    if color[q] == "white":
        k = List[q][1]
        if k != 0:
            Q += List[q][2:2+k]
            for i in List[q][2:2+k]:
                d[i] = min(d[q] + 1, d[i])
    
    color[q] = "black"


for i, dis in enumerate(d[1:], 1):
    print(i, dis)

Submission status: Wrong Answer

Solution code:
#coding: utf-8
inf = 100000000
n = int(input())

List = [0] + [list(map(int,input().split())) for i in range(n)]
color = [0] + ["white" for  i in range(n)]
d = [inf for i in range(n+1)]

s = 1
Q = [s]
d[s] = 0
while Q != []:
    q = Q.pop()
    if color[q] == "white":
        k = List[q][1]
        if k != 0:
            Q += List[q][2:2+k]
            for i in List[q][2:2+k]:
                d[i] = min(d[q] + 1, d[i])
    
    color[q] = "black"


for i, dis in enumerate(d[1:], 1):
    if dis == inf:
        dis = -1
    print(i, dis)

Submission status: Wrong Answer

Solution code:

Submission status: Wrong Answer

Solution code:
N= int(input())
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
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: Wrong Answer

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: Wrong Answer

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(1,N):
    if int(L[i]) == 0:
        L[i] = -1

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

Submission status: Wrong Answer

Solution code:
N= int(input())
E = [input().split()[2:] for _ in range(N)]
frag, T, L,Q = [0]*N, [0]*N, [0]*N, [0]
frag[0] = 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(1,N):
    if int(L[i]) == 0:
        L[i] = -1

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

Submission status: Wrong Answer

Solution code:
N= int(input())
E = [input().split()[2:] for _ in range(N)]
frag, T, L,Q = [0]*N, [0]*N,[0] + [-1]*N, [0]
frag[0] = 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.pop();func(top)

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

Submission status: Wrong Answer

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

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

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

Submission status: Wrong Answer

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

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

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

Submission status: Wrong Answer

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)
        else:return

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

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

Submission status: Wrong Answer

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)
        else:return None
    

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

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

Submission status: Wrong Answer

Solution code:
from queue import Queue

n = int(input())
A = [[0 for i in range(n)] for j in range(n)]
d = [0 for i in range(n)]

for i in range(n):
    u, k, *v = list(map(int, input().split()))
    for j in v:
        A[int(u)-1][int(j)-1] = 1

q = Queue()
q.put(0)
d[0] = 0

while not q.empty():
    u = q.get()
    # print('visited:', u)
    for v in range(n):
        # print(u, v)
        if A[u][v] == 1 and d[v] == 0:
            q.put(v)
            d[v] = d[u] + 1

# print('-========')
for i in range(n):
    print(i, d[i])

Submission status: Wrong Answer

Solution code:
from queue import Queue

n = int(input())
A = [[0 for i in range(n)] for j in range(n)]
d = [-1 for i in range(n)]

for i in range(n):
    u, k, *v = list(map(int, input().split()))
    for j in v:
        A[int(u)-1][int(j)-1] = 1

q = Queue()
q.put(0)
d[0] = 0

while not q.empty():
    u = q.get()
    # print('visited:', u)
    for v in range(n):
        # print(u, v)
        if A[u][v] == 1 and d[v] == -1:
            q.put(v)
            d[v] = d[u] + 1

# print('-========')
for i in range(n):
    print(i, d[i])

Submission status: Wrong Answer

Solution code:
n = int(input())
G = [[] for _ in range(n)]
for _ in range(n):
    u, k, *v = [int(i) for i in input().split()]
    G[u - 1] = v
NIL = 100
Q = [[1, 0]]
F = []
D = [NIL for _ in range(n)]
while Q != []:
    u, d = Q.pop(0)
    if d < D[u-1]:
        D[u-1] = d
    if u not in F:
        F.append(u)
    for v in G[u-1]:
        if v not in F:
            Q.append([v, d+1])

for ni in range(1, n):
    Q = [[ni+1, 0]]
    F = []
    while Q != []:
        u, d = Q.pop(0)
        if u == 1 and d < D[ni]:
            D[ni] = d
        if u not in F:
            F.append(u)
        for v in G[u-1]:
            if v not in F:
                Q.append([v, d+1])

for ni in range(n):
    if D[ni] == NIL:
        print(ni+1, -1)
    else:
        print(ni+1, D[ni])

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
graph = [[] for _ in range(n)]
global Q, S, T
global visited, dis
Q = deque([0])
S = [0] #訪れた順
T = []
visited = [0 for _ in range(n)]
dis = [-1 for _ in range(n)] #初めからの距離
dis[0] = 0
def input_graph(n):
  for _ in range(n):
    node_id, num, *v = list(map(int, input().split()))
    for i in range(num):
      graph[node_id-1].append(v[i]-1)

def bfs(node_id):
  global Q, S
  while Q:
    node_id = Q.popleft()

    for ad_node in graph[node_id]:
      if visited[ad_node] == 1:
        continue
      visited[ad_node] = 1
      dis[ad_node] = dis[node_id] + 1
      S.append(ad_node)
      Q.append(ad_node)

if __name__ == "__main__":
  input_graph(n)
  for i in range(n):
    if visited[i] == 1:
      continue
    visited[i] = 1
    bfs(i)
  for i, d in enumerate(dis):
    print(i, d)

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
graph = [[] for _ in range(n)]
global Q, S, T
global visited, dis
Q = deque([0])
S = [0] #訪れた順
T = []
visited = [0 for _ in range(n)]
dis = [-1 for _ in range(n)] #初めからの距離
dis[0] = 0
def input_graph(n):
  for _ in range(n):
    node_id, num, *v = list(map(int, input().split()))
    for i in range(num):
      graph[node_id-1].append(v[i]-1)

def bfs(node_id):
  global Q, S
  while Q:
    node_id = Q.popleft()

    for ad_node in graph[node_id]:
      if visited[ad_node] == 1:
        continue
      visited[ad_node] = 1
      dis[ad_node] = dis[node_id] + 1
      S.append(ad_node)
      Q.append(ad_node)

if __name__ == "__main__":
  input_graph(n)
  bfs(0)
  for i, d in enumerate(dis):
    print(i, d)

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
graph = [[] for _ in range(n)]
global Q, S, T
global visited, dis
Q = deque([0])
S = [0] #訪れた順
T = []
visited = [0 for _ in range(n)]
dis = [-1 for _ in range(n)] #初めからの距離
dis[0] = 0
def input_graph(n):
  for _ in range(n):
    node_id, num, *v = list(map(int, input().split()))
    for i in range(num):
      graph[node_id-1].append(v[i]-1)

def bfs(node_id):
  global Q, S
  while Q:
    node_id = Q.popleft()

    for ad_node in graph[node_id]:
      if visited[ad_node] == 1:
        continue
      visited[ad_node] = 1
      dis[ad_node] = dis[node_id] + 1
      S.append(ad_node)
      Q.append(ad_node)

if __name__ == "__main__":
  input_graph(n)
  bfs(0)
  for i, d in enumerate(dis):
    print(i+1, d)

Submission status: Wrong Answer

Solution code:
n = int(input())
adj = [list(map(int, input().split()))[2:] for _ in range(n)]
 
d = [-1] * n
 
s = 1
q = []
d[s - 1] = 0
q.append(s)
while len(q):
    u = q.pop()
    v = adj[u - 1]
    for vi in v:
        if d[vi - 1] == -1:
            d[vi - 1] = d[u - 1] + 1
            q.append(vi)
 
 
for i, di in enumerate(d):
    print(i + 1, di)

Submission status: Wrong Answer

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

d = [-1] * n

s = 1
q = []
d[s - 1] = 0
q.append(s)
while len(q):
    u = q.pop()
    v = adj[u - 1]
    for vi in v:
        if d[vi - 1] == -1:
            d[vi - 1] = d[u - 1] + 1
        elif d[vi - 1] > d[u - 1] + 1:
            d[vi - 1] = d[u - 1] + 1            
            q.append(vi)

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

Submission status: Wrong Answer

Solution code:
from sys import stdin

X = [ 0 for i in range(100) ]
d = [ 0 for i in range(100) ]
G = [[ 0 for i in range(100) ] for i in range(100)]
queue = [ 0 for i in range(100) ]

t = 0
head = 0
tail = 0

def BFS(i) :
	global head
	for j in range(n) :
		if G[i][j] == 1 and d[j] == 0 :
			d[j] = d[i] + 1
			queue[head] = j
			head += 1

def tailQ() :
	global tail
	tail += 1
	return queue[tail-1]


n = int(input())
for i in range(n) :
	X[i] = stdin.readline().strip().split()


for i in range(n) :
	for j in range(int(X[i][1])) :
		G[int(X[i][0])-1][int(X[i][j+2])-1] = 1

BFS(0)
while head-tail != 0 : 
	BFS(tailQ())

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

Submission status: Wrong Answer

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_11_C
# Breadth First Search
# Result:
import sys

class Graph(object):
    def __init__(self, size):
        super(Graph, self).__init__()
        self.__size = size
        self.__vertices = [None] * size

    def add_vertex(self, vertex):
        self.__vertices[vertex.id_ - 1] = vertex

    def get_vertex(self, vid):
        return self.__vertices[vid - 1]

    def breadth_first_search(self):
        ds = [-1] * self.__size
        vs = [[]] * self.__size
        vs[0] = [self.get_vertex(1)]
        ds[0] = 0
        vs_idx = 0
        while vs_idx < self.__size and len(vs[vs_idx]) > 0:
            vlst = vs[vs_idx]
            vs_idx += 1
            for vtx in vlst:
                for advid in vtx.adjacents:
                    adv = self.get_vertex(advid)
                    if ds[advid - 1] == -1:
                        ds[advid - 1] = vs_idx
                        vs[vs_idx].append(adv)
        for idx, d in enumerate(ds):
            print '%d %d' % ((idx + 1), d)

    def __str__(self):
        str_ = ''
        for e in self.__vertices:
            str_ += '%s\n' % e
        return str_

class Vertex(object):
    def __init__(self, id_):
        super(Vertex, self).__init__()
        self.id_ = id_
        self.adjacents = []
        self.next_idx = 0

    def add_adjacent(self, avid):
        self.adjacents.append(avid)

    def __str__(self):
        str_ = '%d ' % self.id_
        if len(self.adjacents) == 0:
            str_ += '0'
        else:
            str_ += '%d' % len(self.adjacents)
            for e in self.adjacents:
                str_ += ' %d' % e
        return str_



s = int(sys.stdin.readline().strip())
graph = Graph(s)
for _ in range(0, s):
    vals = [int(x) for x in sys.stdin.readline().strip().split(' ')]
    v = Vertex(vals[0])
    graph.add_vertex(v)
    if vals[1] == 0: continue
    for i in range(0, vals[1]):
        v.add_adjacent(vals[2 + i])

graph.breadth_first_search()

Submission status: Wrong Answer

Solution code:
import sys


def bfs(matrix):
    distances = [-1 for _ in range(len(matrix))]
    queue = [0]
    distances[0] = 0

    while 0 < len(queue):
        node_id = queue.pop(0)  # Dequeue
        distance = distances[node_id]
        for index, candidate in enumerate(matrix[node_id]):
            if candidate == 1 and distances[index] == -1:
                # ???????????¢????¨?????????????????????? node
                queue.append(index)
                distances[index] = distance + 1

    return distances

if __name__ == "__main__":
    # ??????????????????
    lines = [
        "4",
        "1 2 2 4",
        "2 1 4",
        "3 0",
        "4 1 3",
    ]
    # lines = sys.stdin.readlines()
    dimension = int(lines[0])
    matrix = [[0 for _ in range(dimension)] for _ in range(dimension)]

    # Set edge info
    for index, line in enumerate(lines[1:]):
        for edge in [int(x) for x in line.strip().split(" ")[2:]]:
            matrix[index][edge - 1] = 1

    distances = bfs(matrix)
    for index, distance in enumerate(distances):
        print("%d %d" % (index + 1, distance))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python3

def find(id, V, d, dist):
    i = id - 1
    dist[i] = d
    for v in V[i]:
        if dist[v - 1] == -1:
            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: Wrong Answer

Solution code:
def BFS(s, r):
    flag[s] = 1
    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: Wrong Answer

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

def BFS(node):
    node.is_serched = True
    for item in node.link_node:
        if item.distance == -1:
            item.distance = node.distance + 1
    for item in node.link_node:
        if item.is_serched == False:
            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].distance = 0
BFS(node_list[1])

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

Submission status: Wrong Answer

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

def BFS(node):
    node.is_serched = True
    for item in node.link_node:
        if item.distance == -1:
            item.distance = node.distance + 1
        elif item.distance > node.distance + 1:
            item.distance = node.distance + 1
    for item in node.link_node:
        if item.is_serched == False:
            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].distance = 0
BFS(node_list[1])

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

Submission status: Wrong Answer

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)
            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: Wrong Answer

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():
    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: Wrong Answer

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 and e != 1:
            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: Wrong Answer

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)]
frag = [[0 for i in range(n)] for j 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 and frag[s][e] == 0:
            frag[s][e] = 1
            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: Wrong Answer

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)]
frag = [[0 for i in range(n)] for j in range(n)]
temp_d = [0]

def BFS_visit(s, temp_d):
    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 and frag[s][e] < 1:
            frag[s][e] += 1
            BFS_visit(e, temp_d)
        elif M[s][e] == 1 and s != e and frag[s][e] == 1:
            frag[s][e] += 1
            BFS_visit(e, d[s]+1)
def BFS():
    s = 0
    BFS_visit(0, 0)
    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: Wrong Answer

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:
            d[e] = min(d[e], d[s] + 1)

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

Submission status: Wrong Answer

Solution code:
from collections import deque

n = int(input())
g = [None] * n
visited = [0] * n
dist = [-1] * n
queue = deque()

while n:
    l = list(map(int, input().split()))
    connected = [i - 1 for i in l[2:]]
    g[l[0] - 1] = [i - 1 for i in l[2:]]
    n -= 1

queue.append((0, 0))
visited[0] = 1

while queue:
    print(queue)
    i, d = queue.popleft()
    dist[i] = d
    for c in g[i]:
        if not visited[c]:
            visited[c] = 1
            queue.append((c, d + 1))

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

Submission status: Wrong Answer

Solution code:
import sys

n = input()

d = [sys.maxint for i in xrange(n + 1)]
Q = []

color = ['WHITE' for i in xrange(n + 1)]

graph_map = [[0 for j in xrange(n + 1)] for i in xrange(n + 1)]

for i in xrange(1, n + 1):
    tmp = map(int, raw_input().split())
    for j in xrange(tmp[1]):
        graph_map[i][j + 2] = 1

color[1] = 'GRAY'
d[1] = 0
Q.append(1)

while len(Q) != 0:
    u = Q.pop(0)
    print Q
    for v in xrange(1, n + 1):
        if graph_map[u][v] == 1 and color[v] == 'WHITE':
            color[v] = 'GRAY'
            d[v] = d[u] + 1
            Q.append(v)
            print Q
    color[u] = 'BLACK'

for i in xrange(1, n + 1):
    print "%d %d" % (i, d[i])

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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