Java Data Structures Graph depth-first search

Description

Java Data Structures Graph depth-first search


class StackX {/*from  w w w. j a  v a  2 s .c o m*/
   private final int SIZE = 20;
   private int[] st;
   private int top;

   public StackX() // constructor
   {
      st = new int[SIZE]; // make array
      top = -1;
   }

   public void push(int j) // put item on stack
   {
      st[++top] = j;
   }

   public int pop() // take item off stack
   {
      return st[top--];
   }

   public int peek() // peek at top of stack
   {
      return st[top];
   }

   public boolean isEmpty() // true if nothing on stack
   {
      return (top == -1);
   }
}

class Vertex {
   public char label; // label (e.g. 'A')
   public boolean wasVisited;

   public Vertex(char lab) // constructor
   {
      label = lab;
      wasVisited = false;
   }
}

class Graph {
   private final int MAX_VERTS = 20;
   private Vertex vertexList[]; // list of vertices
   private int adjMat[][]; // adjacency matrix
   private int nVerts; // current number of vertices
   private StackX theStack;

   public Graph() {
      vertexList = new Vertex[MAX_VERTS];
      // adjacency matrix
      adjMat = new int[MAX_VERTS][MAX_VERTS];
      nVerts = 0;
      for (int y = 0; y < MAX_VERTS; y++) // set adjacency
         for (int x = 0; x < MAX_VERTS; x++) // matrix to 0
            adjMat[x][y] = 0;
      theStack = new StackX();
   }

   public void addVertex(char lab) {
      vertexList[nVerts++] = new Vertex(lab);
   }

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

   public void displayVertex(int v) {
      System.out.print(vertexList[v].label);
   }

   public void dfs() {
      vertexList[0].wasVisited = true;
      displayVertex(0);
      theStack.push(0);

      while (!theStack.isEmpty()) {
         int v = getAdjUnvisitedVertex(theStack.peek());
         if (v == -1)
            theStack.pop();
         else {
            vertexList[v].wasVisited = true;
            displayVertex(v);
            theStack.push(v);
         }
      }
      for (int j = 0; j < nVerts; j++)
         vertexList[j].wasVisited = false;
   }

   public int getAdjUnvisitedVertex(int v) {
      for (int j = 0; j < nVerts; j++)
         if (adjMat[v][j] == 1 && vertexList[j].wasVisited == false)
            return j;
      return -1;
   }
}

public class Main {
   public static void main(String[] args) {
      Graph theGraph = new Graph();
      theGraph.addVertex('A'); // 0 (start for dfs)
      theGraph.addVertex('B'); // 1
      theGraph.addVertex('C'); // 2
      theGraph.addVertex('D'); // 3
      theGraph.addVertex('E'); // 4

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

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



PreviousNext

Related