| 1 |
# |
| 2 |
# Copyright (C) 2015-2017 FreeIPA Contributors see COPYING for license |
| 3 |
# |
| 4 |
from collections import deque |
| 5 |
|
| 6 |
|
| 7 |
class Graph: |
| 8 |
""" |
| 9 |
Simple oriented graph structure |
| 10 |
|
| 11 |
G = (V, E) where G is graph, V set of vertices and E list of edges. |
| 12 |
E = (tail, head) where tail and head are vertices |
| 13 |
""" |
| 14 |
|
| 15 |
def __init__(self): |
| 16 |
self.vertices = set() |
| 17 |
self.edges = [] |
| 18 |
self._adj = dict() |
| 19 |
|
| 20 |
def add_vertex(self, vertex): |
| 21 |
self.vertices.add(vertex) |
| 22 |
self._adj[vertex] = [] |
| 23 |
|
| 24 |
def add_edge(self, tail, head): |
| 25 |
if tail not in self.vertices: |
| 26 |
raise ValueError("tail is not a vertex") |
| 27 |
|
| 28 |
if head not in self.vertices: |
| 29 |
raise ValueError("head is not a vertex") |
| 30 |
|
| 31 |
self.edges.append((tail, head)) |
| 32 |
self._adj[tail].append(head) |
| 33 |
|
| 34 |
def remove_edge(self, tail, head): |
| 35 |
try: |
| 36 |
self.edges.remove((tail, head)) |
| 37 |
except ValueError: |
| 38 |
raise ValueError( |
| 39 |
"graph does not contain edge: ({0}, {1})".format(tail, head) |
| 40 |
) |
| 41 |
self._adj[tail].remove(head) |
| 42 |
|
| 43 |
def remove_vertex(self, vertex): |
| 44 |
try: |
| 45 |
self.vertices.remove(vertex) |
| 46 |
except KeyError: |
| 47 |
raise ValueError( |
| 48 |
"graph does not contain vertex: {0}".format(vertex) |
| 49 |
) |
| 50 |
|
| 51 |
# delete _adjacencies |
| 52 |
del self._adj[vertex] |
| 53 |
for adj in self._adj.values(): |
| 54 |
adj[:] = [v for v in adj if v != vertex] |
| 55 |
|
| 56 |
# delete edges |
| 57 |
self.edges = [ |
| 58 |
e for e in self.edges if vertex not in (e[0], e[1]) |
| 59 |
] |
| 60 |
|
| 61 |
def get_tails(self, head): |
| 62 |
""" |
| 63 |
Get list of vertices where a vertex is on the right side of an edge |
| 64 |
""" |
| 65 |
return [e[0] for e in self.edges if e[1] == head] |
| 66 |
|
| 67 |
def get_heads(self, tail): |
| 68 |
""" |
| 69 |
Get list of vertices where a vertex is on the left side of an edge |
| 70 |
""" |
| 71 |
return [e[1] for e in self.edges if e[0] == tail] |
| 72 |
|
| 73 |
def bfs(self, start=None): |
| 74 |
""" |
| 75 |
Breadth-first search traversal of the graph from `start` vertex. |
| 76 |
Return a set of all visited vertices |
| 77 |
""" |
| 78 |
if not start: |
| 79 |
start = next(iter(self.vertices)) |
| 80 |
visited = set() |
| 81 |
queue = deque([start]) |
| 82 |
|
| 83 |
while queue: |
| 84 |
vertex = queue.popleft() |
| 85 |
if vertex not in visited: |
| 86 |
visited.add(vertex) |
| 87 |
queue.extend(set(self._adj.get(vertex, [])) - visited) |
| 88 |
return visited |