At first glance, a graph is a lot like a tree or a binary tree, but it can be problematic to build on an object-based approach, because the graph can grow to a very large extent, and it is inefficient to use objects to represent them.
First we need to define a class of graphs, where the adjacency table is represented by the Adj array, which is the node array associated with the node, and the marked array is used to indicate whether the node has been accessed, in depth-first search and breadth-first search.
function Graph (v) {//Graph Class this.vertices=v;//node this.edges=0;//number of edges this.adj=[];//array holds vertex number for (Var i=0;i<this.vertices ; i++) {this.adj[i]=[];//sub-array stores adjacent vertices}this.addedge=addedge;//add edges this.showgraph=showgraph;//Show Graph this.dfs=dfs;// Depth first search this.bfs=bfs;//breadth First search this.marked=[];//identity bit array for (Var i=0;i<this.vertices;i++) {// Add an this.marked[i]=false identity bit to all nodes;}}
Then you need to define a function to add a bilateral relationship with the following code:
function Addedge (v,w) {//Add Edge This.adj[v].push (w);//Add W to the adjacent vertex list of V This.adj[w].push (v);//Add V to the adjacent vertex list of W this.edges++;/ /number of sides plus one}
Next, define a function that shows the graph relationship, with the following code:
function Showgraph () {//Display figure for (Var i=0;i<this.vertices;i++) {document.write (i+ "); for (Var j=0;j< this.vertices;j++) {if (this.adj[i][j]!=undefined) {//display and nodes adjacent to the node document.write (this.adj[i][j]+ "");}} document.write ("<br>");}}
Here's what you can do to test:
G=new Graph (5); G.addedge (0,1); G.addedge (0,2); G.addedge (1,3); G.addedge (2,4); G.showgraph ();
The experimental results are as follows:
// Results
//0-> 1 2
//1-> 0 3
//2-> 0 4
//3-> 1
4-> 2
A diagram shows it. The next section will cover the implementation of breadth-first and depth-first search.
Representation of the graph JavaScript