0
I’m trying to do an in-depth search using a stack, but it’s making a mistake on a if
and I don’t know why.
package Grafos;
import java.io.*;
import java.util.*;
public class Grafo {
LinkedList<Integer> Arestas [];
int n;
int qtd_Arestas = 0;
public Grafo(int n){
this.n = n;
Arestas = new LinkedList[n];
for (int i=0; i<n; ++i)
Arestas[i] = new LinkedList();
}
public void Adiciona_aresta(int origem, int destino){
Arestas[origem].add(destino);
qtd_Arestas++;
}
public int DFS(int S, boolean visited[], int contador){
visited[S] = true;
ListIterator<Integer> v = Arestas[S].listIterator();
while(v.hasNext()) {
n = v.next();
System.out.println(S + ">>" + n);
if(!visited[n]){
contador = DFS(n,visited,contador+1);
}
}
return contador+1;
}
public void DFS_ini(int S){
boolean Visitados[] = new boolean [n];
int contador = 0;
int b = DFS(S,Visitados,contador);
System.out.println("____________________________________________________");
}
public void Pilha_DFS(int S) {
boolean visitados [] = new boolean [n];
for(int i = 0; i < n;i++){
visitados[i] = false;
}
int gatilho;
int topo;
visitados[S] = true;
Stack pilha = new Stack();
pilha.push(S);
while(!pilha.isEmpty()){
topo = (int) pilha.firstElement();
if(Arestas[S].isEmpty()){
gatilho = 1;
break;
}
for(int linha : Arestas[S]) {
if(visitados[linha] == false){//Erro aqui
System.out.println(S + ">>" + linha);
visitados[linha] = true;
pilha.add(linha);
S = linha;
}else if(visitados[topo] == true){
pilha.remove(topo);
}
}
}
}
}
Error presented:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Grafos.Grafo.Pilha_DFS(Grafo.java:55)
at Grafos.Main.main(Main.java:12)
What’s the mistake?
ArrayIndexOutOfBoundsException
?– Victor Stafusa
What is the type of
Arestas
? The code implies that it’s something likeList<Integer>[]
, but I have some doubts.– Victor Stafusa
Stack
isjava.util.Stack
or is some other stack implementation?– Victor Stafusa
I’ll put the full code to a better understanding.
– Amanda Nunes
Code complete right now
– Amanda Nunes
I answered based on the code that was originally there. I will update the answer shortly considering the full code.
– Victor Stafusa