Skip to content

Instantly share code, notes, and snippets.

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 jcready/162d7d976f5817efcaecb14f72c61b8e to your computer and use it in GitHub Desktop.
Save jcready/162d7d976f5817efcaecb14f72c61b8e to your computer and use it in GitHub Desktop.
Parse stringified graph (‘a->b,b->c, a->c’) and find all the nodes that can reach a given node
export const parseGraph = s => s
.split(',')
.map(edge => edge.trim().split('->'))
.reduce((adjacency, [a, b]) => {
if (!adjacency.has(a)) {
adjacency.set(a, new Set())
}
if (!adjacency.has(b)) {
adjacency.set(b, new Set())
}
adjacency.get(b).add(a)
return adjacency
}, new Map())
export const nodesWhichReach = (graph, node) => {
const visited = new Set()
if (!graph.has(node)) return visited
const q = []
q.push(node)
while (q.length) {
const currentNode = q.shift()
visited.add(currentNode)
for (let n of graph.get(currentNode)) {
if (!visited.has(n)) q.push(n)
}
}
visited.delete(node)
return visited
}
/*
const graph = parseGraph('a->b,b->c,q->b,z->q,n->m,m->w,w->p')
nodesWhichReach(graph, 'c') // Set(4) {"b", "a", "q", "z"}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment