-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch-breadthFirst.js
More file actions
67 lines (66 loc) · 1.61 KB
/
Copy pathsearch-breadthFirst.js
File metadata and controls
67 lines (66 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var Queue = function(){
this.items = [];
}
Queue.prototype.enqueue = function(obj){
this.items.push(obj);
}
Queue.prototype.dequeue = function(){
return this.items.shift();
}
Queue.prototype.isEmpty = function(){
var empty = this.items.length === 0 ;
return empty ;
}
//@param graph is in the form of an adgacency list
function doFBS (graph , source){
var bfsInfo = [];
for (var i = 0 ; i < graph.length ; i++){
bfsInfo[i] = {
distance : null ,
predecessor : null
}
}
bfsInfo[source].distance = 0 ;
var queue = new Queue();
queue.enqueue(source);
// till now , we have a graph with verteces have distances and predescessors equal to @null
while (queue.isEmpty() === false){
var vertex = queue.dequeue();
for (var j = 0 ; j < graph[vertex].length ; j++){
if (bfsInfo[graph[vertex][j]].distance === null){
bfsInfo[graph[vertex][j]].distance = bfsInfo[vertex].distance + 1 ;
bfsInfo[graph[vertex][j]].predecessor = vertex ;
queue.enqueue(graph[vertex][j]);
}
}
}
return bfsInfo ;
}
var adjList = [
[],
[9,5,6,4],
[11,5,4,3],
[5,2,8,10],
[6,1,2,7],
[1,2,3,7],
[9,1,4,8],
[4,5,10],
[6,3,14],
[1,6],
[3,7,11,13],
[2,10,12],
[11,13,14],
[10,12],
[8,12]
];
function findShortestPath (graph, from, to){
var path = to ;
var bfsInfo = doFBS(graph,from);
var predecessor = bfsInfo[to].predecessor;
while(predecessor != null){
path += " < " + predecessor ;
predecessor = bfsInfo[predecessor].predecessor ;
}
return path ;
}
console.log(findShortestPath(adjList,1,12));