def graph():
nk = int(input('Введите количество вершин графа: '))
nl = nk
array = [[0 for i in range(nl)] for i in range(nl)]
for i in range(nl):
for j in range(nl):
k1 = i + 1
k2 = j + 1
if k1 == k2:
continue
if array[i][j] == 0:
print(f'Есть ли связь между вершиной {k1} и {k2}? ')
connection = input('')
if connection == 'да':
array[i][j] = 1
array[j][i] = 1
if connection == 'нет':
array[i][j] = 0
array[j][i] = 0
print('Матрица смежности:')
for i in range(nk):
print(array[i])
return array
def matrix_to_list(array):
graph = {}
for i, node in enumerate(array):
adj = []
for j, connected in enumerate(node):
if connected:
adj.append(j)
graph[i] = adj
return graph
a = graph()
print(f"Cвязный список: {matrix_to_list(a)}")
N = matrix_to_list(a)
def bfs(graph, v):
allk = []
Q = []
Q.append(v)
while Q != []:
v = Q.pop(0)
allk.append(v)
for n in graph[v]:
if n not in Q and n not in allk:
Q.append(n)
return allk
print(bfs(N, 1))
v = bfs(N, 1)
d = {}
for i in v:
d[i + 1] = [i + 1 for i in N[i]]
print(d)
50$
Обсуждают сегодня