Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

January 3, 2010

The Complete Graph Class (including DFS prog)

import java.util.Stack;




public class Graph {

private final int MAX_VERTS = 20;
private Vertex[] vertexList;
private int totalVertices;
private int adjMat[][];

public Graph(){
vertexList = new Vertex[MAX_VERTS];
adjMat = new int[MAX_VERTS][MAX_VERTS];
totalVertices = 0;

for(int i = 0 ; i < MAX_VERTS ; i++){
for(int j = 0 ; j < MAX_VERTS ; j++){
adjMat[i][j] = 0;
}
}
}

public int getAdjUnvisitedVertex(int v){
if(v >= 0 && v< MAX_VERTS){
for(int i = 0 ; i < MAX_VERTS ; i++){
if(adjMat[v][i] == 1 && vertexList[i].visited == false){
return i;
}
}
}
return -1;
}
public void addVertex(char lab){
vertexList[totalVertices++] = new Vertex(lab);
}

public void dfs(){
vertexList[0].visited = true;
Stack dfsStack = new Stack();
dfsStack.push(0);
displayVertex(0);

while(!dfsStack.isEmpty()){
Integer currrent = dfsStack.peek();
int adjVe = this.getAdjUnvisitedVertex(currrent);
if(adjVe >= 0){
vertexList[adjVe].visited = true;
dfsStack.push(adjVe);
displayVertex(adjVe);
}else{
dfsStack.pop();
}

}
for(int j=0; j< totalVertices; j++) // reset flags
vertexList[j].visited = false;

}

public void addEdge(int start , int end){
adjMat[start][end] = 1;
adjMat[end][start] = 1;
}

public void displayVertex(int v){
if(v >= 0 && v < MAX_VERTS){
System.out.println(vertexList[v].label);
}
}
}
class Vertex{
public char label;
public boolean visited;

public Vertex(char lab){
label = lab;
visited = false;
}
}

Main Class :


public class GraphMain {

/**
* @param args
*/
public static void main(String[] args) {
Graph g = new Graph();
g.addVertex('A'); //0
g.addVertex('B'); //1
g.addVertex('C'); //2
g.addVertex('D'); //3
g.addVertex('E'); //4
g.addVertex('F'); //5
g.addVertex('G'); //6


g.addEdge(0, 1); // AB
g.addEdge(1, 2); // BC
g.addEdge(0, 3); // AD
g.addEdge(3, 4); // DE
g.addEdge(5, 6); // DE

System.out.print("Visits: ");
g.dfs(); // depth-first search
System.out.println();

}

}

No comments: