Define the node class first
class Vertex{ char label; boolean wasVisited; publicVertex(char label){ this.label = label; false; }}
Figure:
Class graph{Private Final intMax_verts = -;PrivateVertex vertexlist[];//Node list Private intAdjmat[][];//adjacency matrix Private intNverts;//Number of nodes PrivateStack Thestack;//Assistance Stack Public Graph() {vertexlist =NewVertex[max_verts]; Adjmat =New int[Max_verts] [Max_verts]; Nverts =0; for(inti =0; i < max_verts; i++) { for(intj =0; J < Max_verts; J + +) Adjmat[i][j] =0; } Thestack =NewStack (); } Public void Addvertex(CharLab) {vertexlist[nverts++] =NewVertex (Lab); } Public void Addedge(intStartintEnd) {Adjmat[start][end] =1; Adjmat[end][start] =1; } Public void Displayvertex(intV) {System.out.print (Vertexlist[v].label); }//Depth-First search /** * Depth First search to get the vertex farthest from the starting point, and then return * * Rule 1: If possible, access an adjacent unreachable vertex, mark it, and put it on the stack * Rule 2: When Rule 1 o'clock cannot be executed, If the stack is not empty, a vertex is popped from the stack * * Rule 3: If rule 1 and rule 2 cannot be executed, the entire search process is completed */ Public void DFS() {vertexlist[0].wasvisited =true;//Starting from the first node, marked as visitedDisplayvertex (0);//PrintThestack.push (0);//into the stack while(!thestack.isempty ()) {//Get an inaccessible adjacency node intv = Getadjunvisiedvertex ((int) Thestack.peek ());if(v = =-1)//No such node, the point access is completeThestack.pop ();Else{//Continue to visitvertexlist[v].wasvisited =true; Displayvertex (v); Thestack.push (v); } }//After all nodes have been accessed, reset all nodes to access state for(intj =0; J < Nverts; J + +) {vertexlist[j].wasvisited =false; } }//Gets the unreachable node that is adjacent to the V node Public int Getadjunvisiedvertex(intV) { for(inti =0; i < nverts; i++) {if(Adjmat[v][i] = =1&& vertexlist[i].wasvisited = =false){returnI } }return-1; }}
Test:
Graph thegraph = new graph ();Thegraph. Addvertex(' A ');Thegraph. Addvertex(' B ');Thegraph. Addvertex(' C ');Thegraph. Addvertex(' D ');Thegraph. Addvertex(' E ');Thegraph. Addedge(0,1);Thegraph. Addedge(1,2);Thegraph. Addedge(0,3);Thegraph. Addedge(3,4);Thegraph. DFS();
Search by Depth First:
ABCDE
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java implementation diagram with adjacency matrix and depth-first search