about summary refs log tree commit diff
path: root/deepmind/dijkstra.py
diff options
context:
space:
mode:
authorWilliam Carroll <wpcarro@gmail.com>2020-01-29T14·43+0000
committerWilliam Carroll <wpcarro@gmail.com>2020-01-29T14·43+0000
commit5c9079a41059e077f2b71b68eb83ff9fcb2e38d1 (patch)
treedce7e3566b04213228fb3c92fc593ca18841d972 /deepmind/dijkstra.py
parentfb9380ba268b3cd27372acadb87b14cc96163374 (diff)
Splice ./universe directory into ./
Manually merging:
- README.md: I added the description from universe/README.md into the heading of
  dotfiles/README.md.
- .envrc: dotfiles/.envrc was a superset of universe/.envrc
- .gitignore: Adding some of the ignored patterns from universe/.gitignore to
  dotfiles/.gitignore

Everything else here should be a simple rename.
Diffstat (limited to 'deepmind/dijkstra.py')
-rw-r--r--deepmind/dijkstra.py26
1 files changed, 26 insertions, 0 deletions
diff --git a/deepmind/dijkstra.py b/deepmind/dijkstra.py
new file mode 100644
index 000000000000..6975dbe4d1d6
--- /dev/null
+++ b/deepmind/dijkstra.py
@@ -0,0 +1,26 @@
+# Doing a practice implementation of Dijkstra's algorithm: a priority-first
+# search.
+from heapq import heappush, heappop
+
+
+class Node(object):
+    def __init__(self, value, children):
+        self.value = value
+        self.children = children
+
+
+def shortest_path(a, b):
+    """Return the shortest path from `a` to `b`."""
+    q = []
+    seen = set()
+    heappush((a.value, a, [a]), q)
+
+    while q:
+        d, node, path = heappop(q)
+        if node == b:
+            return path
+        seen.add(node)
+        for child in node.children:
+            if child not in seen:
+                heappush((d + child.value, child, path + [child]), q)
+    raise Exception("Path between nodes A and B does not exist.")