In this case, the graph inside the existing matrix is traversed with depth precedence.
The first advantage of depth is the FIFO feature of the stack. After this traversal, you can find the most adjacent node to continue the traversal. To achieve depth first, you also need to add an Access ID to the node to determine if the node has been accessed.
Source:
Packagemygraph;ImportJava.util.Stack; Public classDfs_vertex {
Create a node class that we needclassVertex {Private Charlable; Private intVal; Private Booleanwasvisited; Vertex (Charlable) { This. lable =lable; } Vertex () {}}Private Charlable;//Matrix Element Privatevertex[][] List =NewVertex[20][20]; Privatevertex[] Vertexlist =NewVertex[20]; Private intNverts;//Current vertex subscriptDfs_vertex () { This. Nverts = 0; for(inti = 0; I < 20; i + +) { for(intj = 0; J < 20; J + +) {List[i][j]=NewVertex (); } } } //Add a vertex Public voidAddvertex (Charlable) {Vertexlist[nverts++] =NewVertex (lable); } //Add an edge Public voidAddedge (intStartintend) {List[start][end].val= 1; List[end][start].val= 1; } //Print Matrix Public voidPrintmatrix () { for(inti = 0; i < nverts; i++) { for(intj = 0; J < Nverts; J + +) {System.out.print (list[i][j].val); } System.out.println (); } } //Display characters Public voidShowvertex (intv) {System.out.print (vertexlist[v].lable+ "\ T"); } //obtaining contiguous unreachable nodes Public intGetadjunvisitedvertex (intv) { for(intj = 0; J < Nverts; J + +) { if((List[v][j].val = = 1) && (vertexlist[j].wasvisited = =false)) { returnJ; } } return-1; } //DFS Public voidDFS () {Stack<Integer> s =NewStack (); vertexlist[0].wasvisited =true; Showvertex (0); S.push (0); intv; while(S.size () > 0) {v=Getadjunvisitedvertex (S.peek ()); if(v = =-1) {s.pop (); }Else{vertexlist[v].wasvisited=true; Showvertex (v); S.push (v); } } for(intj = 0; J < Nverts; J + +) {vertexlist[j].wasvisited=false; } }}
Test procedure:
Public Static voidMain (string[] args) {Dfs_vertex ds=NewDfs_vertex (); Ds.addvertex (' A ');//0Ds.addvertex (' B ');//1Ds.addvertex (' C ');//2Ds.addvertex (' D ');//3Ds.addvertex (' E ');//4Ds.addedge (0, 1);// A-BDs.addedge (0, 3);//a-dDs.addedge (1, 4);//b-eDs.addedge (3, 4);//d-eDs.addedge (4, 2);//e-cDs.printmatrix (); Ds. DFS (); }
Test results:
10001000011000101110A B E C D
Data structure Java version of depth first-figure (12)