Skip to content

Commit

Permalink
add Dijstra SP
Browse files Browse the repository at this point in the history
  • Loading branch information
shellfly committed Feb 5, 2020
1 parent 538902e commit 95330f5
Show file tree
Hide file tree
Showing 4 changed files with 178 additions and 0 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ Try to keep the interface and variable name consistent with the original book wh
* [LazyPrimMST](algs4/lazy_prim_mst.py)
* [PrimMST](algs4/prim_mst.py)
* [KruskalMST](algs4/kruskal_mst.py)
* Shortest Paths
* [EdgeWeightedDigraph](algs4/edge_weighted_digraph.py)
* [DijkstraSP](algs4/dijkstra_sp.py)
* [AcyclicSP](algs4/acyclic_sp.py)
* [Bellman-FordSP](algs4/bellman_ford_sp.py)

* 5 STRING

Expand Down
86 changes: 86 additions & 0 deletions algs4/dijkstra_sp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""
* Execution: python dijkstra_sp.py input.txt s
* Data files: https://algs4.cs.princeton.edu/44sp/tinyEWD.txt
* https://algs4.cs.princeton.edu/44sp/mediumEWD.txt
* https://algs4.cs.princeton.edu/44sp/largeEWD.txt
*
* Dijkstra's algorithm. Computes the shortest path tree.
* Assumes all weights are nonnegative.
*
* % python dijkstra_sp.py tinyEWD.txt 0
* 0 to 0 (0.00)
* 0 to 1 (1.05) 0->4 0.38 4->5 0.35 5->1 0.32
* 0 to 2 (0.26) 0->2 0.26
* 0 to 3 (0.99) 0->2 0.26 2->7 0.34 7->3 0.39
* 0 to 4 (0.38) 0->4 0.38
* 0 to 5 (0.73) 0->4 0.38 4->5 0.35
* 0 to 6 (1.51) 0->2 0.26 2->7 0.34 7->3 0.39 3->6 0.52
* 0 to 7 (0.60) 0->2 0.26 2->7 0.34
*
* % python dijkstra_sp.py mediumEWD.txt 0
* 0 to 0 (0.00)
* 0 to 1 (0.71) 0->44 0.06 44->93 0.07 ... 107->1 0.07
* 0 to 2 (0.65) 0->44 0.06 44->231 0.10 ... 42->2 0.11
* 0 to 3 (0.46) 0->97 0.08 97->248 0.09 ... 45->3 0.12
* 0 to 4 (0.42) 0->44 0.06 44->93 0.07 ... 77->4 0.11
* ...
*
"""

from algs4.edge_weighted_digraph import EdgeWeightedDigraph
from algs4.index_min_pq import IndexMinPQ
from algs4.stack import Stack

POSITIVE_INFINITY = 999999.0


class DijkstraSP:
def __init__(self, g, s):
self.edgeTo = [None for _ in range(g.V)]
self.distTo = [float("inf") for _ in range(g.V)]
for v in range(g.V):
self.distTo[v] = POSITIVE_INFINITY
self.distTo[s] = 0.0
self.pq = IndexMinPQ(g.V)
self.pq.insert(s, self.distTo[s])
while not self.pq.is_empty():
self.relax(g, self.pq.del_min())

def relax(self, g, v):
for e in g.adj[v]:
w = e.To()
if self.distTo[w] > self.distTo[v]+e.weight:
self.distTo[w] = self.distTo[v] + e.weight
self.edgeTo[w] = e
if self.pq.contains(w):
self.pq.change(w, self.distTo[w])
else:
self.pq.insert(w, self.distTo[w])

def has_path_to(self, v):
return self.distTo[v] < POSITIVE_INFINITY

def path_to(self, v):
if not self.has_path_to(v):
return None
edges = Stack()
e = self.edgeTo[v]
while e != None:
edges.push(e)
e = self.edgeTo[e.From()]
return edges


if __name__ == "__main__":
import sys
graph = EdgeWeightedDigraph(file=open(sys.argv[1]))
s = int(sys.argv[2])
sp = DijkstraSP(graph, s)
for t in range(graph.V):
if sp.has_path_to(t):
print("%d to %d (%.2f) " % (s, t, sp.distTo[t]), end="")
for e in sp.path_to(t):
print(e, " ", end="")
print()
else:
print("%d to %d no path" % (s, t))
20 changes: 20 additions & 0 deletions algs4/directed_edge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class DirectedEdge:
def __init__(self, v, w, weight):
self.v = v
self.w = w
self.weight = weight

def __str__(self):
return "%d->%s %.5f" % (self.v, self.w, self.weight)

def __lt__(self, other):
return self.weight < other.weight

def __gt__(self, other):
return self.weight > other.weight

def From(self):
return self.v

def To(self):
return self.w
67 changes: 67 additions & 0 deletions algs4/edge_weighted_digraph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""
* Execution: python edge_weighted_graph.py filename.txt
* Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt
* https://algs4.cs.princeton.edu/43mst/mediumEWG.txt
* https://algs4.cs.princeton.edu/43mst/largeEWG.txt
*
* An edge-weighted undirected graph, implemented using adjacency lists.
* Parallel edges and self-loops are permitted.
*
* % python edge_weighted_graph.py tinyEWD.txt
* 8 vertices, 15 edges
* 0: 0->2 0.26000 0->4 0.38000
* 1: 1->3 0.29000
* 2: 2->7 0.34000
* 3: 3->6 0.52000
* 4: 4->7 0.37000 4->5 0.35000
* 5: 5->1 0.32000 5->7 0.28000 5->4 0.35000
* 6: 6->4 0.93000 6->0 0.58000 6->2 0.40000
* 7: 7->3 0.39000 7->5 0.28000
*
"""
from algs4.bag import Bag
from algs4.directed_edge import DirectedEdge


class EdgeWeightedDigraph:
def __init__(self, v=0, **kwargs):
self.V = v
self.E = 0
self.adj = {}
for v in range(self.V):
self.adj[v] = Bag()

if 'file' in kwargs:
# init a digraph by a file input
in_file = kwargs['file']
self.V = int(in_file.readline())
for v in range(self.V):
self.adj[v] = Bag()
E = int(in_file.readline())
for i in range(E):
v, w, weight = in_file.readline().split()
self.add_edge(DirectedEdge(int(v), int(w), float(weight)))

def __str__(self):
s = "%d vertices, %d edges\n" % (self.V, self.E)
for i in range(self.V):
adjs = " ".join([str(x) for x in self.adj[i]])
s += "%d: %s\n" % (i, adjs)
return s

def add_edge(self, e):
self.adj[e.From()].add(e)
self.E += 1

def edges(self):
edges = []
for v in range(self.V):
for e in self.adj[v]:
edges.append(e)
return edges


if __name__ == "__main__":
import sys
graph = EdgeWeightedDiraph(file=open(sys.argv[1]))
print(graph)

0 comments on commit 95330f5

Please sign in to comment.