bfs dfs
by sramnan
JavaScript
function bfs(graph,root,goal){
var queue = [];
var visited = [];
queue.push(root);
visited[root] = 1;
while(queue.length !==0){
var current = queue.shift();
console.log("bfs" + current);
if(current == goal){
return true;
}
else {
for(var i=0;i<graph[current].length;i++){
if(!visited[i] && graph[current][i] == 1){
queue.push(i);
visited[i] = 1;
}
}
}
}
return false;
}
function dfs(graph,root,goal){
var stack = [];
var visited = [];
stack.push(root);
visited[root] = 1;
while(stack.length !==0){
var current = stack.pop();
console.log("dfs" + current);
if(current == goal){
return true;
}
else {
for(var i=0;i<graph[current].length;i++){
if(!visited[i] && graph[current][i] == 1){
stack.push(i);
visited[i] = 1;
}
}
}
}
return false;
}
var graph = [[0 , 1 , 1, 0],
[1 , 0 , 0, 0],
[1 , 0 , 0, 1],
[0 , 0 , 1, 0]
];
console.log(dfs(graph,0,4));
console.log(bfs(graph,0,4));