Skip to content

Instantly share code, notes, and snippets.

@AykutSarac
Created August 18, 2021 12:27
Show Gist options
  • Save AykutSarac/4c1266b7ae98f8708639a45d51a481e5 to your computer and use it in GitHub Desktop.
Save AykutSarac/4c1266b7ae98f8708639a45d51a481e5 to your computer and use it in GitHub Desktop.
depthFirstSearch (array to map)
// 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