-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphutils.py
96 lines (70 loc) · 2.75 KB
/
graphutils.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
from os import path
class Graph :
def __init__(self, edges, directed=False): # Espera => edges = [('A', 'B'), ('B', 'C'), ('A','C')]
self.directed = directed
self.neighbors = {}
self.add_edges(edges)
def add_edges(self, edges): #Adiciona as arestas em forma de dicionario de listas
for x, y, in edges:
self.neighbors.setdefault(x, []).append(y)
if self.directed:
self.neighbors.setdefault(y, [])
else:
self.neighbors.setdefault(y, []).append(x)
def get_edges(self): #Devolve todas as arestas do grafo
edges = []
for key in self.neighbors.keys():
for value in self.neighbors[key]:
edges.append((key, value))
return edges
def get_vertices(self): #Devolve todos os vertices
return list(self.neighbors.keys())
def egde_exists(self, edge:tuple): #Devolse se uma aresta existe no grafo ou não
return edge[0] in self.neighbors and edge[1] in self.neighbors[edge[0]]
# ============================================================
def get_dependents(graph, vertex):
visited = {key:False for key in graph.get_vertices()}
initial_vertex = vertex
relations = []
direct_depentens = []
indirect_depentens = []
def rec_dfs(graph, vertex):
visited[vertex] = True
for neighbor in graph.neighbors[vertex]:
if not visited[neighbor]:
if vertex == initial_vertex:
direct_depentens.append(neighbor)
else:
indirect_depentens.append(neighbor)
relations.append((vertex, neighbor))
rec_dfs(graph, neighbor)
rec_dfs(graph, vertex)
return [direct_depentens, indirect_depentens, relations]
# ============================================================
def get_dependencies(graph, vertex):
visited = {key:False for key in graph.get_vertices()}
target_vertex = vertex
dependencies = []
dependencies_paths = []
def rec_dfs(graph, vertex):
visited[vertex] = True
dependencies.append(vertex)
if vertex == target_vertex:
dependencies_paths.append(dependencies.copy())
else:
for neighbor in graph.neighbors[vertex]:
if not visited[neighbor]:
rec_dfs(graph, neighbor)
dependencies.pop()
visited[vertex] = False
for vertex in graph.get_vertices():
if not visited[vertex]:
rec_dfs(graph, vertex)
result = []
for paths in dependencies_paths:
#print(paths)
temp = (set(paths) - set(result))
result = result + list(temp)
result.remove(target_vertex)
result.sort()
return result