/
Grafo_Matriz_Adjacencia.py
92 lines (83 loc) · 2.62 KB
/
Grafo_Matriz_Adjacencia.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
from Grafo_Interface import IGrafo
from string import ascii_uppercase
class Grafo(IGrafo):
def __init__(self, orientado = False):
self.__matriz = []
self.__orientado = orientado
self.__vazio = True
def DefinirN(self, n):
self.n = n
for i in range(0, self.n):
self.__matriz.append([0 for j in range(0, self.n)])
return self.__matriz
def V(self):
return [i for i in range(0, self.n)]
def E(self):
arestas = []
u = None
v = None
for i in range(0, self.n):
for j in range(0, self.n):
if self.__matriz[i][j] != 0:
u = ascii_uppercase[i]
v = ascii_uppercase[j]
if not self.__orientado:
arestas.append((u, v))
else:
if (u, v) not in arestas:
arestas.append((u, v))
arestas.sort()
return arestas
def RemoverAresta(self, u = '', v = ''):
i = ascii_uppercase.index(u)
j = ascii_uppercase.index(v)
self.__matriz[i][j] = 0
if not self.__orientado:
self.__matriz[j][i] = 0
return [(u, v), (v, u)]
return [(u, v)]
def AdicionarAresta(self, u = '', v = ''):
self.__vazio = False
i = ascii_uppercase.index(u)
j = ascii_uppercase.index(v)
self.__matriz[i][j] = 1
if not self.__orientado:
self.__matriz[j][i] = 1
return self.__matriz
def SaoViz(self, u = '', v = ''):
i = ascii_uppercase.index(u)
j = ascii_uppercase.index(v)
if not self.__orientado:
return self.__matriz[i][j] == 1 and self.__matriz[i][j] == 1
else:
return self.__matriz[i][j] == 1
def Viz(self, v, Tipo="*", Fechada=False):
i = ascii_uppercase.index(v)
vizinhos_de_v = []
for j in range(0, self.n):
if self.__matriz[i][j] == 1:
vizinhos_de_v.append(ascii_uppercase[j])
if Fechada:
vizinhos_de_v.append(v)
return vizinhos_de_v
def __str__(self):
if self.__vazio:
return 'Grafo vazio'
else:
return (
'Matriz:\n\n{}'.format(
self.__matriz
).replace(
'], ', ' \n'
).replace(
'\n[', '\n\t'
).replace(
']', ''
).replace(
'[', ''
).replace(
', ', ' '
).replace(
"'", ''
)
)