about summary refs log tree commit diff
path: root/scratch/facebook/graph-coloring.py
diff options
context:
space:
mode:
authorWilliam Carroll <wpcarro@gmail.com>2020-11-23T23·21+0000
committerWilliam Carroll <wpcarro@gmail.com>2020-11-23T23·21+0000
commit9549dbb2666e1032ad1f55218e68fd7ac636485e (patch)
tree70c089928040ed103dc567de3f2a99c5804ac5ea /scratch/facebook/graph-coloring.py
parentc00eed469ccd5f4b53d98ceeeba32963dd593ed8 (diff)
Update BFS impls
I've subtly been implementing breadth-first traversals in graphs
incorrectly. The change is subtle, but updating `seen` needs to happen
immediately after queuing an item.

The results will remain the same, but the runtimes will differ dramatically. I
didn't notice this until I attempted to complete LeetCode's "count islands"
challenge, and LeetCode rejected my solution because it could not finish before
timing out. After looking at other candidates' solutions and comparing them to
mine, I couldn't see any difference... except for this subtle difference.

This SO answer provides a helpful explanation:
https://stackoverflow.com/questions/45623722/marking-node-as-visited-on-bfs-when-dequeuing

The take-away lesson here is to always call `seen.add(..)` immediately after
enqueuing.
Diffstat (limited to 'scratch/facebook/graph-coloring.py')
-rw-r--r--scratch/facebook/graph-coloring.py4
1 files changed, 2 insertions, 2 deletions
diff --git a/scratch/facebook/graph-coloring.py b/scratch/facebook/graph-coloring.py
index 17588166c871..e5b6d9c89332 100644
--- a/scratch/facebook/graph-coloring.py
+++ b/scratch/facebook/graph-coloring.py
@@ -25,10 +25,10 @@ class GraphNode(object):
         while xs:
             node = xs.popleft()
             result.append('{} ({})'.format(node.label, str(node.color)))
-            seen.add(node.label)
             for c in node.neighbors:
                 if c.label not in seen:
                     xs.append(c)
+                    seen.add(node.label)
         return ', '.join(result)
 
 def color_graph(graph, d):
@@ -40,11 +40,11 @@ def color_graph(graph, d):
     while xs:
         x, color = xs.popleft()
         x.color = color
-        seen.add(x.label)
         for c in x.neighbors:
             if c.label not in seen:
                 palette.advance()
                 xs.append((c, palette.get()))
+                seen.add(x.label)
 
 a = GraphNode('a')
 b = GraphNode('b')