JS graph data structure processing----neighbor list, breadth first search, minimum path

Source: Internet
Author: User

Neighbor table
Add each vertex first, then join the Edge

Queue
var Queue = (function () {
var item = new Weakmap ();
Class queue{
Constructor () {
Item.set (this,[]);
}
Enqueue (ele) {
var ls = item.get (this);
Ls.push (ele);
}
Dequeue () {
var ls = item.get (this);
return Ls.shift ();
}
Size () {
var ls = item.get (this);
return ls.length;
}
Front () {
var ls = item.get (this);
return ls[0];
}
IsEmpty () {
var ls = item.get (this);
return!ls.length;
}
Print () {
var ls = item.get (this);

for (var i = 0; i < ls.length; i++) {
Console.log (' ${ls[i]} ');
}
}
}
return Queue;
})();


Depth-First Search

Breadth First Search
function Graph () {
var vertices = []; Store all the vertices
var adjlist = {}; Stores adjacent vertices of all vertices

This.addvertex = function (v) {
if (!adjlist[v]) {
Vertices.push (v);
ADJLIST[V] = [];
}else{
throw new Error ("The vertex already exists");
}
};
var initializecolor = function () {
var color = {};
for (var i = 0; i < vertices.length; i++) {
Color[vertices[i]] = ' white ';
}
return color;
}

This.addedge = function (v,w) {
if (Adjlist[v] && adjlist[w]) {
Adjlist[v].push (w);
Adjlist[w].push (v);

}else{
throw new Error ("link non-existent vertex");
}
};
this.tostring = function () {
var s = ';
for (var i=0; i<vertices.length; i++) {//{10}
s + = Vertices[i] + ' + ';
var neighbors = adjlist[vertices[i]]; {11}
for (var j=0; j<neighbors.length; J + +) {//{12}
s + = neighbors[j] + ';
}
s + = ' \ n '; {13}
}
return s;
};
This.print = function () {
Console.log (This.tostring ());
};

Breadth-first search, find each point
Search for neighboring points for each point
1, initialize, all the vertex states are white, that is, no traversal to
2, through the point, get an array of adjacent points, traverse the adjacent points
3. If the neighboring point is white, it becomes gray. and join the queue, into the next loop


THIS.BFS = function (v,callback) {
var color = Initializecolor ();
Queue = new Queue ();
Queue.enqueue (v);
while (!queue.isempty ()) {
var u = queue.dequeue ();
Neighbors = Adjlist[u];
Color[u] = ' grey ';
for (var i = 0; i < neighbors.length; i++) {
var w = neighbors[i];
if (color[w] = = = ' White ') {
COLOR[W] = ' grey ';
Queue.enqueue (w);
}
}
Color[u] = "BLACK";
if (callback) {
Callback (U);
}
}
};

Breadth-first algorithm to calculate the distance of each vertex
This. BFS = function (v) {
var color = Initializecolor ();
Queue = new Queue ();
Queue.enqueue (v);
d = []; Distance List
Pred = []; Forward Point
for (var i=0; i<vertices.length; i++) {
D[vertices[i]] = 0;
Pred[vertices[i]] = null;
}
while (!queue.isempty ()) {
var u = queue.dequeue ();
Neighbors = Adjlist[u];
Color[u] = ' grey ';
for (var i = 0; i < neighbors.length; i++) {
var w = neighbors[i];
if (color[w] = = = ' White ') {
COLOR[W] = ' grey ';
D[W] = D[u] + 1;
PRED[W] = u;
Queue.enqueue (w);
}
}
Color[u] = "BLACK";

}
Return {
Distances:d,
predecessors:pred
}
}

This.getpath = function (u) {
//Print Shortest path
//The adjacent point before backtracking
var shortestpath = this. BFS (U);
var Fromvertex = vertices[0];
for (var i=1; i<vertices.length; i++) {

var Tovertex = vertices[i],
Path = [];
for (var V=tovertex; v!== Fromvertex;
V=shortestpath.predecessors[v]) {
Path.push (v);
}
Path.push (Fromvertex);
var s = path.join ("-");

Console.log (s);
}
}

}


var graph = new graph ();
var myvertices = [' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ']; {7}
for (var i=0; i<myvertices.length; i++) {//{8}
Graph.addvertex (Myvertices[i]);
}
Graph.addedge (' A ', ' B '); {9}
Graph.addedge (' A ', ' C ');
Graph.addedge (' A ', ' D ');
Graph.addedge (' C ', ' D ');
Graph.addedge (' C ', ' G ');
Graph.addedge (' D ', ' G ');
Graph.addedge (' D ', ' H ');
Graph.addedge (' B ', ' E ');
Graph.addedge (' B ', ' F ');
Graph.addedge (' E ', ' I ');

GRAPH.BFS ("A", function (Cnode) {
Console.log (Cnode);
});

Console.log (graph. BFS ("A"));
Graph.getpath (' A ');

/*
If you want to calculate the shortest path in a weighted graph (for example, the shortest distance between cities) breadth-first search may not be appropriate.
* The Dijkstra algorithm solves the single source shortest path problem. The Bellman-ford algorithm solves a negative Benquan value.
Single source shortest path problem. A * search algorithm solves the problem of finding the shortest path between a pair of vertices, which uses the rule of thumb to speed up search
The cable process. The Floyd-warshall algorithm solves the problem of finding the shortest path between all vertex pairs.
*
* */

  

JS graph data structure processing----neighbor list, breadth first search, minimum path

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.