Professional Documents
Culture Documents
java
1 import java.util.Stack;
2
3 public class DFSGraph {
4
5 // number of node
6 int size;
7 // list of type adj_list has head of type Node
8 adjlist[] array;
9
10
11 public DFSGraph(int size) {
12 this.size=size;
13 array=new adjlist [this.size];
14
15 // initialize to array
16 for (int i = 0; i < size ; i++)
17 {
18 array[i]=new adjlist();
19 array[i].head=null;
20
21 }// end for
22
23 }//constructor
24
25
26
27
28 // Method to add new node take src which determine reference node, dest which determine
value in node
29 public void addnode(int src, int dest)
30 {
31 Node n =new Node(dest,null);
32 n.next=array[src].head;
33 array[src].head=n;
34
35 }// end method addnode
36
37
38 // Method to explorer all node in tree take startvertex to determine first step
39
40 public void DFSExplore (int startvertex)
41 {
42
43 // array determine node visited or no
44 Boolean [] visited =new Boolean [size];
45 //initialize to array
46 for (int i=0;i<size;i++)
47 visited[i]=false;
48
49 //initialize stack
50 Stack<Integer> s=new Stack<Integer>();
51 s.push(startvertex);
52
53 // while stack isn't empty continuous
54 while (!s.isEmpty()){
55
56 // last item in stack
57 int n =s.pop();
58 //retrieval in its position because has still children
59 s.push(n);
60 // it is visited
61 visited[n]=true;
Page 1
DFSGraph.java
Page 2