SageScroll18144

DFS

Aug 6th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. @SuppressWarnings("unchecked")
  4.  
  5. public class DFS {
  6.  
  7.     private static int n;
  8.  
  9.     public static void dfs(int node, ArrayList<Integer>[] graph, boolean[] vizinhos){
  10.        
  11.         Stack<Integer> pilha = new Stack<>();
  12.         pilha.push(node);
  13.         vizinhos[node] = true;
  14.         if(graph[node].size()>0){
  15.  
  16.             for (int i = 0; i < graph[node].size(); i++) {
  17.                 int v = graph[node].get(i);
  18.                 if (vizinhos[v] == false) {
  19.                     dfs(v, graph, vizinhos);
  20.                 }else{
  21.                     pilha.pop();
  22.                 }
  23.             }
  24.         }else{
  25.             pilha.pop();
  26.         }
  27.     }
  28.     public static void main(String[] args) {
  29.  
  30.         Scanner s = new Scanner(System.in);
  31.         n = 3;
  32.        
  33.         ArrayList<Integer>[] graph = new ArrayList[n];
  34.         for (int i = 0; i < n; i++) {
  35.             graph[i] =  new ArrayList<>();
  36.         }
  37.         boolean[] vizinhos = new boolean[n];
  38.        
  39.         for (int i = 0; i < vizinhos.length; i++) {
  40.             vizinhos[i] = false;
  41.         }
  42.         for (int i = 0; i < n; i++) {
  43.             String input = s.nextLine();
  44.             if (input.length() > 0) {
  45.                 for (String var : input.split(" ")) {
  46.                     graph[i].add(Integer.parseInt(var));
  47.                 }
  48.            }
  49.            else{
  50.                continue;
  51.            }
  52.         }
  53.         s.close();      
  54.         dfs(0, graph, vizinhos);
  55.         for (int i = 0; i < vizinhos.length; i++) {
  56.             System.out.println(vizinhos[i]);
  57.         }
  58.        
  59.     }
  60.  
  61.    
  62. }
Advertisement
Add Comment
Please, Sign In to add comment