Created
January 20, 2017 03:05
-
-
Save msullivan/8d145c803d159f34a9dc4630be2c09c9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
def build_rgraph(graph): | |
rgraph = {k: set() for k in graph.keys()} | |
for u in graph.keys(): | |
for v in graph[u]: | |
rgraph[v].add(u) | |
return rgraph | |
def dfs(graph, seen, val, start): | |
stack = [start] | |
while stack: | |
v = stack.pop() | |
if v in seen: continue | |
seen[v] = val | |
stack.extend(graph[v]) | |
return seen | |
def detours_search(graph, rgraph, path): | |
ti = {} | |
for i in range(len(path)): | |
dfs(rgraph, ti, i, path[i]) | |
fi = {} | |
for i in reversed(range(len(path))): | |
dfs(graph, fi, i, path[i]) | |
nobes = set() | |
for u in graph.keys(): | |
if u in ti and u in fi and ti[u] <= fi[u]: | |
nobes.add(u) | |
return nobes | |
def detours(graph, path): | |
return detours_search(graph, build_rgraph(graph), path) | |
#### | |
test_graph = { | |
'a': {'b'}, | |
'b': {'c', 'f'}, | |
'c': {'d'}, | |
'd': {'e'}, | |
'e': set(), | |
'f': {'g'}, | |
'g': {'d', 'h'}, | |
'h': {'f', 'i'}, | |
'i': {'h'} | |
} | |
test_path = "abfgde" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment