|
| 1 | +package DataAndAlgoL.Chpt9GraphAlgorithms; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | +class Vertex{ |
| 6 | + public char label; |
| 7 | + public boolean visited; |
| 8 | + public Vertex(char lab){ |
| 9 | + label=lab; |
| 10 | + visited=false; |
| 11 | + } |
| 12 | +} |
| 13 | +public class DFSGraph { |
| 14 | + final int maxVertices=20; //max number of vertices in the graph |
| 15 | + Vertex[] vertexList; //array of vertices |
| 16 | + int[][] adjMatrix; //matrix that will hold the vertices |
| 17 | + int vertexCount; |
| 18 | + Stack theStack; |
| 19 | + |
| 20 | + |
| 21 | + public DFSGraph(){ |
| 22 | + vertexList= new Vertex[maxVertices]; //new array of vertices of size maxVertices (20) |
| 23 | + adjMatrix= new int[maxVertices][maxVertices];// matrix that will contain the vertices with matrix size 20x20 |
| 24 | + vertexCount=0; |
| 25 | + for(int i=0; i< maxVertices; i++){ |
| 26 | + for(int j=0; j<maxVertices; j++){ |
| 27 | + adjMatrix[i][j]=0; //populate the entire matrix with value 0 for each cell in row and column |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + theStack= new Stack(); |
| 32 | + |
| 33 | + } |
| 34 | + |
| 35 | + public void addVertex(char lab){ |
| 36 | + vertexList[vertexCount++]= new Vertex(lab); //each char lab will be put in vertex list starting from 0 (vertexCount) |
| 37 | + } |
| 38 | + |
| 39 | + //creates an edge with value 1 for the position we want to add the edge |
| 40 | + public void addEdge(int start, int end){ |
| 41 | + adjMatrix[start][end]=1; |
| 42 | + adjMatrix[end][start]=1; |
| 43 | + } |
| 44 | + |
| 45 | + public void displayVertex(int v){ |
| 46 | + System.out.println(vertexList[v].label); //displays the char value of the vertex at position v |
| 47 | + } |
| 48 | + |
| 49 | + public void dfs(){ |
| 50 | + vertexList[0].visited=true; |
| 51 | + displayVertex(0); |
| 52 | + theStack.push(0); |
| 53 | + while(!theStack.isEmpty()){ |
| 54 | + int v=getAdjUnvisitedVertex((int) theStack.peek()); |
| 55 | + if(v ==-1){ |
| 56 | + theStack.pop(); |
| 57 | + }else{ |
| 58 | + vertexList[v].visited=true; |
| 59 | + displayVertex(v); |
| 60 | + theStack.push(v); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + //reset flags |
| 65 | + for(int i=0; i<vertexCount; i++){ |
| 66 | + vertexList[i].visited=false; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + public int getAdjUnvisitedVertex(int v){ |
| 71 | + for(int i=0; i< vertexCount; i++){ |
| 72 | + if(adjMatrix[v][i]==1 && vertexList[i].visited==false){ |
| 73 | + return i; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return -1; |
| 78 | + } |
| 79 | +} |
0 commit comments