title: Java - Adjacency Matrix and DFS
body: <p>I've been working on a program to implement a DFS in Java (by taking an adjacency matrix as input from a file). Basically, assuming vertices are traveled in numerical order, I would like to print the order that vertices become dead ends, the number of connected components in the graph, the tree edges and the back edges. But I'm not completely there yet. When I run my program, I get the number "1" as output, and nothing more. I've tried debugging certain parts of the DFS class, but I still can't quite figure out where I'm going wrong. Here is my code:</p>
  
  <p>A basic "Driver" class:</p>
  
  <pre><code>import java.io.File;
  import java.io.FileNotFoundException;
  import java.util.Scanner;
  
  public class Driver {
  
  public static void main(String[] args) throws FileNotFoundException {
      Scanner scanner = new Scanner(new File("sample1.txt"));
      scanner.useDelimiter("[\\s,]+");
  
      int input = scanner.nextInt();
      int[][] adjMatrix = new int[8][8];
  
      for(int i=0; i &lt; input; i++) {
          for (int j=0; j &lt; input; j++) {
               adjMatrix[i][j] = scanner.nextInt();
          }
      }
      scanner.close();
  
      new DFS(adjMatrix);
  
  }
  
  }
  </code></pre>
  
  <p>DFS class:</p>
  
  <pre><code>import java.util.Stack;
  
  public class DFS {
  Stack&lt;Integer&gt; stack;
  int first;
  int[][] adjMatrix;
  int[] visited = new int[7];
  
  public DFS(int[][] Matrix) {
  
      this.adjMatrix = Matrix;
      stack = new Stack&lt;Integer&gt;();
      int[] node = {0, 1, 2, 3, 4, 5, 6};
      int firstNode = node[0];
      depthFirstSearch(firstNode, 7);
  }
  
  public void depthFirstSearch(int first,int n){
       int v,i;
  
       stack.push(first);
  
       while(!stack.isEmpty()){
           v = stack.pop();
           if(visited[v]==0) {
               System.out.print("\n"+(v+1));
               visited[v]=1;
           }
           for (i=0;i&lt;n;i++){
               if((adjMatrix[v][i] == 1) &amp;&amp; (visited[i] == 0)){
                   stack.push(v);
                   visited[i]=1;
                   System.out.print(" " + (i+1));
                   v = i;
               }
           }
       }
  }
  }
  </code></pre>
  
  <p>And the matrix from the input file looks like this:</p>
  
  <pre><code>0 1 0 0 1 1 0 0
  1 0 0 0 0 1 1 0
  0 0 0 1 0 0 1 0
  0 0 1 0 0 0 0 1
  1 0 0 0 0 1 0 0
  1 1 0 0 1 0 0 0
  0 1 1 0 0 0 0 1
  0 0 0 1 0 0 1 0
  </code></pre>