-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
52 lines (38 loc) · 1.1 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
from collections import deque
def bfs_shortest_path(adj_matrix, start, end):
n = len(adj_matrix)
visited = [False] * n
distance = [-1] * n
queue = deque([start])
visited[start] = True
distance[start] = 0
while queue:
current = queue.popleft()
for neighbor in range(n):
if adj_matrix[current][neighbor] == 1 and not visited[neighbor]:
visited[neighbor] = True
distance[neighbor] = distance[current] + 1
queue.append(neighbor)
if neighbor == end:
return distance[neighbor]
return -1
def main():
import sys
input = sys.stdin.read
data = input().split()
index = 0
n = int(data[index])
index += 1
adj_matrix = []
for i in range(n):
row = list(map(int, data[index:index + n]))
adj_matrix.append(row)
index += n
start = int(data[index]) - 1
end = int(data[index + 1]) - 1
if start == end:
print(0)
else:
print(bfs_shortest_path(adj_matrix, start, end))
if __name__ == "__main__":
main()