-
Notifications
You must be signed in to change notification settings - Fork 0
/
implementacao2.py
98 lines (91 loc) · 2.8 KB
/
implementacao2.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import matplotlib.pyplot as plt
import networkx as nx
################# FUNÇÃO PARA IMPRIMIR ####################
def imprimir(temp):
caminho=temp[0]
componentes = temp[-1]
for i in range(componentes):
print('Componente: '+str(i+1))
for j in caminho[i]:
print(str(j)+" ", end='')
print('\n---------------------')
###################### FUNÇÃO DE BUSCA POR PROFUNDIDADE #############
def busca_profundidade(G: nx.Graph):
visitados=[]
saida=[]
vetor_aux=[]
comp_conexas = 0
def prof(v):
for i in G.neighbors(v):
if i not in visitados:
visitados.append(i)
vetor_aux.append(i)
prof(i)
for i in G.nodes:
if i not in visitados:
if (len(vetor_aux)>0):
saida.append(vetor_aux.copy())
vetor_aux.clear()
comp_conexas+=1
vetor_aux.append(i)
visitados.append(i)
prof(i)
saida.append(vetor_aux.copy())
return (saida, comp_conexas)
#####################################################################
###################### FUNÇÃO DE BUSCA POR AMPLITUDE ################
def busca_largura(G:nx.Graph):
fila=[]
li_comp=[]
visitados=[]
comp_cone=0
saida=[]
index=0
def check_largura(G:nx.Graph):
for i in fila:
fila.remove(i)
for j in G.neighbors(i):
if j not in visitados:
visitados.append(j)
fila.append(j)
li_comp.append(j)
check_largura(G)
for i in G.nodes():
if i not in visitados:
visitados.append(i)
fila.append(i)
li_comp.append(i)
check_largura(G)
comp_cone= comp_cone+1
saida.append([])
saida[index].extend(li_comp.copy())
index=index+1
li_comp.clear()
return(saida, comp_cone)
#####################################################################
######################## FUNÇÃO PRINCIPAL ###########################
arquivo = open('grafo2', 'r')
nvertices =int(arquivo.readline())
vertices = tuple(arquivo.readline().split())
narestas = int(arquivo.readline())
lista_arestas = []
for i in range(narestas):
lista_arestas.append(arquivo.readline().strip().replace(' ', ''))
grafo = nx.Graph()
grafo.add_nodes_from(vertices)
grafo.add_edges_from(lista_arestas)
profundidade=busca_profundidade(grafo)
print("--> Algoritmo DFS")
imprimir(profundidade)
print()
print()
print('=================================================')
print()
print("--> Algoritmo BFS")
largura=(busca_largura(grafo))
imprimir(largura)
nx.draw_networkx(grafo,with_labels=True,
pos=nx.planar_layout(grafo),
node_color='r',
edge_color='b')
plt.show()