Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- @SuppressWarnings("unchecked")
- public class DFS {
- private static int n;
- public static void dfs(int node, ArrayList<Integer>[] graph, boolean[] vizinhos){
- Stack<Integer> pilha = new Stack<>();
- pilha.push(node);
- vizinhos[node] = true;
- if(graph[node].size()>0){
- for (int i = 0; i < graph[node].size(); i++) {
- int v = graph[node].get(i);
- if (vizinhos[v] == false) {
- dfs(v, graph, vizinhos);
- }else{
- pilha.pop();
- }
- }
- }else{
- pilha.pop();
- }
- }
- public static void main(String[] args) {
- Scanner s = new Scanner(System.in);
- n = 3;
- ArrayList<Integer>[] graph = new ArrayList[n];
- for (int i = 0; i < n; i++) {
- graph[i] = new ArrayList<>();
- }
- boolean[] vizinhos = new boolean[n];
- for (int i = 0; i < vizinhos.length; i++) {
- vizinhos[i] = false;
- }
- for (int i = 0; i < n; i++) {
- String input = s.nextLine();
- if (input.length() > 0) {
- for (String var : input.split(" ")) {
- graph[i].add(Integer.parseInt(var));
- }
- }
- else{
- continue;
- }
- }
- s.close();
- dfs(0, graph, vizinhos);
- for (int i = 0; i < vizinhos.length; i++) {
- System.out.println(vizinhos[i]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment