22 - python & all web labs
This commit is contained in:
66
labPython/lab22/task_2.py
Normal file
66
labPython/lab22/task_2.py
Normal file
@@ -0,0 +1,66 @@
|
||||
import random
|
||||
from collections import deque
|
||||
|
||||
|
||||
def create_file():
|
||||
n = random.randint(4, 7)
|
||||
with open("FileName", "w") as f:
|
||||
f.write(str(n) + "\n")
|
||||
for i in range(n):
|
||||
row = [str(random.randint(0, 1)) for _ in range(n)]
|
||||
f.write(" ".join(row) + "\n")
|
||||
|
||||
|
||||
def read_graph():
|
||||
try:
|
||||
with open("FileName") as f:
|
||||
n = int(f.readline())
|
||||
m = [list(map(int, f.readline().split())) for _ in range(n)]
|
||||
return n, m
|
||||
except:
|
||||
return None, None
|
||||
|
||||
|
||||
def bfs(n, m, start, L):
|
||||
dist = [-1] * n
|
||||
q = deque([start])
|
||||
dist[start] = 0
|
||||
while q:
|
||||
v = q.popleft()
|
||||
for u in range(n):
|
||||
if m[v][u] == 1 and dist[u] == -1:
|
||||
dist[u] = dist[v] + 1
|
||||
if dist[u] <= L:
|
||||
q.append(u)
|
||||
return {i for i in range(n) if dist[i] != -1 and dist[i] <= L}
|
||||
|
||||
|
||||
while True:
|
||||
print("\n1 - создать файл")
|
||||
print("2 - выполнить задачу")
|
||||
print("0 - выход")
|
||||
c = input(">> ")
|
||||
if c == "1":
|
||||
create_file()
|
||||
print("FileName создан")
|
||||
elif c == "2":
|
||||
n, m = read_graph()
|
||||
if n is None:
|
||||
print("ошибка чтения FileName")
|
||||
continue
|
||||
try:
|
||||
k1 = int(input("K1: ")) - 1
|
||||
k2 = int(input("K2: ")) - 1
|
||||
L = int(input("L: "))
|
||||
except:
|
||||
print("ошибка ввода")
|
||||
continue
|
||||
s1 = bfs(n, m, k1, L)
|
||||
s2 = bfs(n, m, k2, L)
|
||||
res = sorted([x + 1 for x in s1 & s2])
|
||||
if res:
|
||||
print("результат:", *res)
|
||||
else:
|
||||
print(-1)
|
||||
elif c == "0":
|
||||
break
|
||||
Reference in New Issue
Block a user