Advertisement
jamius19

DFS Graph

May 30th, 2017
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.40 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class DFS {
  5.     public static void main(String[] args) {
  6.         try{
  7.             File f = new File(System.getProperty("user.home") + "/Desktop/input.txt");
  8.             Scanner stdin = new Scanner(f);
  9.            
  10.             int size = stdin.nextInt();
  11.            
  12.             // Data Structures Initialization
  13.             int[][] adjMatrix = new int[size][size];
  14.             boolean[] isStacked = new boolean[size];
  15.             boolean[] isPrinted = new boolean[size];
  16.             Stack<Integer> stack = new Stack<Integer>();
  17.            
  18.             // Matrix Input
  19.             for (int i = 0; i < size; i++) {
  20.                 for (int j = 0; j < size; j++) {
  21.                     adjMatrix[i][j] = stdin.nextInt();
  22.                 }
  23.             }                  
  24.            
  25.             // First node input
  26.             stdin = new Scanner(System.in);
  27.             System.out.println("Enter a node between 0 to " + (size - 1) + "?");
  28.             int choice = stdin.nextInt();
  29.            
  30.             // Setting first node in queue
  31.             stack.push(choice);
  32.             isStacked[choice] = true;  
  33.            
  34.             // Main Loop
  35.             main:
  36.             while(!stack.isEmpty()){
  37.                 int currentNode = stack.peek();
  38.                
  39.                 if(!isPrinted[currentNode]){
  40.                     isPrinted[currentNode] = true;
  41.                     System.out.println(currentNode);
  42.                 }
  43.                
  44.                 for (int i = 0; i < size; i++) {
  45.                     if(adjMatrix[currentNode][i] == 1 && !isStacked[i]){
  46.                         isStacked[i] = true;
  47.                         stack.push(i);
  48.                         continue main;
  49.                     }
  50.                 }          
  51.                
  52.                 stack.pop();               
  53.             }          
  54.            
  55.         } catch (Exception e){
  56.             e.printStackTrace();
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement