Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class DFS {
- public static void main(String[] args) {
- try{
- File f = new File(System.getProperty("user.home") + "/Desktop/input.txt");
- Scanner stdin = new Scanner(f);
- int size = stdin.nextInt();
- // Data Structures Initialization
- int[][] adjMatrix = new int[size][size];
- boolean[] isStacked = new boolean[size];
- boolean[] isPrinted = new boolean[size];
- Stack<Integer> stack = new Stack<Integer>();
- // Matrix Input
- for (int i = 0; i < size; i++) {
- for (int j = 0; j < size; j++) {
- adjMatrix[i][j] = stdin.nextInt();
- }
- }
- // First node input
- stdin = new Scanner(System.in);
- System.out.println("Enter a node between 0 to " + (size - 1) + "?");
- int choice = stdin.nextInt();
- // Setting first node in queue
- stack.push(choice);
- isStacked[choice] = true;
- // Main Loop
- main:
- while(!stack.isEmpty()){
- int currentNode = stack.peek();
- if(!isPrinted[currentNode]){
- isPrinted[currentNode] = true;
- System.out.println(currentNode);
- }
- for (int i = 0; i < size; i++) {
- if(adjMatrix[currentNode][i] == 1 && !isStacked[i]){
- isStacked[i] = true;
- stack.push(i);
- continue main;
- }
- }
- stack.pop();
- }
- } catch (Exception e){
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement