2015-08-05 07:37:05 +08:00
|
|
|
from collections import OrderedDict
|
2015-08-03 18:24:38 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Node:
|
|
|
|
|
|
|
|
def __init__(self, id):
|
|
|
|
self.id = id
|
2015-08-05 07:37:05 +08:00
|
|
|
self.visited = False
|
|
|
|
self.adjacent = OrderedDict() # key = node, val = weight
|
2015-08-03 18:24:38 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Graph:
|
|
|
|
|
|
|
|
def __init__(self):
|
2015-08-05 07:37:05 +08:00
|
|
|
self.nodes = OrderedDict() # 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
|
|
|
|
|
|
|
|
def add_edge(self, source, dest, weight=0):
|
|
|
|
if source not in self.nodes:
|
|
|
|
self.add_node(source)
|
|
|
|
if dest not in self.nodes:
|
|
|
|
self.add_node(dest)
|
2015-08-05 07:37:05 +08:00
|
|
|
self.nodes[source].adjacent[self.nodes[dest]] = weight
|