fork download
  1. def DFS(a, vert):
  2. visited = []
  3. order = []
  4. arr = [a]
  5.  
  6. while arr:
  7. curr = arr.pop()
  8. if curr not in visited:
  9. visited.append(curr)
  10. order.append(curr)
  11. arr.extend(sorted(vert[curr], reverse=True))
  12.  
  13. return " ".join(map(str, order)) + "\n"
  14.  
  15. def BFS(a, vert):
  16. visited = []
  17. order = []
  18. arr = [a]
  19.  
  20. while arr:
  21. curr = arr.pop(0)
  22. if curr not in visited:
  23. visited.append(curr)
  24. order.append(curr)
  25. arr.extend(sorted(vert[curr]))
  26.  
  27. return " ".join(map(str, order)) + "\n"
  28.  
  29. output = ""
  30. counter = 1
  31.  
  32. for t in range(int(input())):
  33. output += f"graph {counter}\n"
  34. mapOfAngels = {}
  35. for n in range(int(input())):
  36. p = input().split()
  37. i = int(p[0])
  38. m = int(p[1])
  39. w = []
  40.  
  41. c2 = 2
  42. for wc in range(m):
  43. w.append(int(p[c2]))
  44. c2 += 1
  45.  
  46. mapOfAngels[i] = w
  47.  
  48. while True:
  49. p2 = input().split()
  50. a = int(p2[0])
  51. method = int(p2[1])
  52. if a == 0 and method == 0:
  53. break
  54.  
  55. if method == 0:
  56. output += DFS(a, mapOfAngels)
  57. pass
  58. elif method == 1:
  59. output += BFS(a, mapOfAngels)
  60. pass
  61.  
  62. counter += 1
  63.  
  64. print(output)
Success #stdin #stdout 0.03s 9768KB
stdin
3
6
1 2 3 4
2 2 3 6
3 2 1 2
4 1 1
5 0
6 1 2
5 1
1 0
1 0
0 0
10
1 6 3 5 6 7 8 9
2 1 9
3 2 1 5
4 5 6 7 8 9 10
5 4 1 3 7 8
6 3 1 4 7
7 5 1 4 5 6 8
8 5 1 4 5 7 10
9 3 1 2 4
10 2 4 8
7 1
1 0
2 1
4 1
7 1
0 0
2
1 0
2 0
1 1
0 0
stdout
graph 1
5
1 3 2 6 4
1 3 2 6 4
graph 2
7 1 4 5 6 8 3 9 10 2
1 3 5 7 4 6 8 10 9 2
2 9 1 4 3 5 6 7 8 10
4 6 7 8 9 10 1 5 2 3
7 1 4 5 6 8 3 9 10 2
graph 3
1