2015-08-23 20:08:46 +08:00
|
|
|
from enum import Enum # Python 2 users: Run pip install enum34
|
|
|
|
|
|
|
|
|
|
|
|
class State(Enum):
|
2016-06-27 05:48:32 +08:00
|
|
|
unvisited = 0
|
|
|
|
visiting = 1
|
2015-08-23 20:08:46 +08:00
|
|
|
visited = 2
|
2015-08-03 18:24:38 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Node:
|
|
|
|
|
|
|
|
def __init__(self, id):
|
|
|
|
self.id = id
|
2015-08-23 20:08:46 +08:00
|
|
|
self.visit_state = State.unvisited
|
2016-06-27 05:48:32 +08:00
|
|
|
self.adjacent = {} # key = node, val = weight
|
2015-08-03 18:24:38 +08:00
|
|
|
|
2015-08-05 18:14:44 +08:00
|
|
|
def __str__(self):
|
|
|
|
return str(self.id)
|
|
|
|
|
2016-06-27 05:48:32 +08:00
|
|
|
def add_neighbor(self, neighbor, weight=0):
|
|
|
|
self.adjacent[neighbor] = weight
|
|
|
|
|
2015-08-03 18:24:38 +08:00
|
|
|
|
|
|
|
class Graph:
|
|
|
|
|
|
|
|
def __init__(self):
|
2016-06-27 05:48:32 +08:00
|
|
|
self.nodes = {} # key = node id, val = node
|
2015-08-03 18:24:38 +08:00
|
|
|
|
|
|
|
def add_node(self, id):
|
|
|
|
node = Node(id)
|
|
|
|
self.nodes[id] = node
|
|
|
|
return node
|
|
|
|
|
2016-06-27 05:48:32 +08:00
|
|
|
def add_edge(self, id_source, id_dest, weight=0):
|
|
|
|
if id_source not in self.nodes:
|
|
|
|
self.add_node(id_source)
|
|
|
|
if id_dest not in self.nodes:
|
|
|
|
self.add_node(id_dest)
|
|
|
|
self.nodes[id_source].add_neighbor(self.nodes[id_dest], weight)
|
|
|
|
|
|
|
|
def add_undirected_edge(self, source, dest, weight=0):
|
|
|
|
self.add_edge(source, dest, weight)
|
|
|
|
self.nodes[dest].add_neighbor(self.nodes[source], weight)
|