Created
August 18, 2021 12:27
-
-
Save AykutSarac/4c1266b7ae98f8708639a45d51a481e5 to your computer and use it in GitHub Desktop.
depthFirstSearch (array to map)
This file contains 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
// Initialize Depth First Search | |
// see https://en.wikipedia.org/wiki/Depth-first_search | |
const depthFirstSearch = (graph, source) => { | |
console.log(source); | |
for (let neighbour of graph.get(source)) { | |
depthFirstSearch(graph, neighbour); | |
} | |
}; | |
// Either integer or string itself can be used here | |
const graph = [ | |
["a", "b"], | |
["a", "c"], | |
["b", "d"], | |
["d", "f"], | |
["c", "e"] | |
]; | |
const graphToDictionary = (graph) => { | |
const adjacencyList = new Map(); | |
const keys = [...new Set(graph.flat())]; | |
keys.forEach((key) => { | |
adjacencyList.set(key, []); | |
}); | |
for (let i = 0; i < graph.length; i++) { | |
adjacencyList.get(graph[i][0]).push(graph[i][1]); | |
} | |
return adjacencyList; | |
}; | |
const dictionary = graphToDictionary(graph); | |
depthFirstSearch(dictionary, "a"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment