Created
November 28, 2016 19:51
-
-
Save jmsevold/0844b1d25a21221d9cdd0971204bc6a2 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
/* | |
1.Create an adjacency list to represent a graph of alphabetical letters as follows: | |
A | |
B C | |
D E H | |
F G | |
2. Write a function that takes a graph, a node (a letter) as a starting point, and lastly a node to search for. Return true if exists, and false if it does not | |
*/ | |
const graph = { | |
A: ['B','C'], | |
B: ['D','E'], | |
C: ['H'], | |
D: [], | |
E: ['F','G'], | |
F: [], | |
G: [], | |
H: ['G'] | |
} | |
class Queue { | |
constructor() { | |
this.items = []; | |
} | |
enqueue(nodeList) { | |
this.items = this.items.concat(nodeList); | |
} | |
dequeue() { | |
return this.items.shift(); | |
} | |
isEmpty() { | |
return this.items.length === 0; | |
} | |
} | |
var nodeNotVisited = (list,item) => { | |
if (list.indexOf(item) === -1) { | |
return true; | |
} | |
return false; | |
}; | |
function bfs(graph,startingNode,targetNode){ | |
let queue = new Queue(); | |
visitedNodes = []; | |
queue.enqueue(graph[startingNode]); | |
while (!queue.isEmpty()){ | |
let node = queue.dequeue(); | |
if(nodeNotVisited(visitedNodes,node)){ | |
if(node === targetNode){ | |
return true; | |
} | |
else{ | |
visitedNodes.push(node); | |
queue.enqueue(graph[node]); | |
} | |
} | |
} | |
return false; | |
} | |
bfs(graph,'A','Z'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment