-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.py
79 lines (63 loc) · 2.12 KB
/
solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class Edge:
def __init__(self, vertex1, vertex2):
self.vertex1 = vertex1
self.vertex2 = vertex2
class VisitResult:
CANCEL_THIS_NODE = 0
CONTINUE = 1
CANCEL_ALL = 2
class Vertex:
def __init__(self, id):
self.id = id
self.edge_list = []
def add_edge_to(self, other):
self.edge_list.append(Edge(self, other))
def dfs(self, visit_function):
visited = set()
to_visit = [(self, 0)]
while len(to_visit) > 0:
vertex, depth = to_visit.pop(0)
result = visit_function(vertex, depth)
if result == VisitResult.CANCEL_THIS_NODE:
continue
elif result == VisitResult.CANCEL_ALL:
return
elif result == VisitResult.CONTINUE:
visited.add(vertex.id)
for edge in vertex.edge_list:
if edge.vertex2.id not in visited:
to_visit.insert(0, (edge.vertex2, depth + 1))
def bfs(self, visit_function):
visited = set()
to_visit = [(self, 0)]
while len(to_visit) > 0:
vertex, depth = to_visit.pop(0)
result = visit_function(vertex, depth)
if result == VisitResult.CANCEL_THIS_NODE:
continue
elif result == VisitResult.CANCEL_ALL:
return
elif result == VisitResult.CONTINUE:
visited.add(vertex.id)
for edge in vertex.edge_list:
if edge.vertex2.id not in visited:
to_visit.append([edge.vertex2, depth + 1])
def connect(vertex1, vertex2):
vertex1.add_edge_to(vertex2)
vertex2.add_edge_to(vertex1)
n = int(input())
vertices = [Vertex(id) for id in range(n)]
x, y = map(int, input().split())
m = int(input())
for _ in range(m):
a, b = map(int, input().split())
connect(vertices[a - 1], vertices[b - 1])
answer = -1
def on_visit(node, depth):
global answer
if node.id == y - 1:
answer = depth
return VisitResult.CANCEL_ALL
return VisitResult.CONTINUE
vertices[x - 1].dfs(on_visit)
print(answer)