Skip to content

Instantly share code, notes, and snippets.

@msullivan
Created January 20, 2017 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msullivan/8d145c803d159f34a9dc4630be2c09c9 to your computer and use it in GitHub Desktop.
Save msullivan/8d145c803d159f34a9dc4630be2c09c9 to your computer and use it in GitHub Desktop.
#!/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