I am studying for an algorithm test and I ended up finding some problems implementing the DFS ( Depht-First Search / depth search) > Stack .
static void emProfundidade(ArrayList<Node> grafo, Node origem) {
Stack<Node> pilha = new Stack<>();
for (int i = 0; i < grafo.size(); i++) {
grafo.get(i).visitado = false;
}
pilha.push(origem);
origem.setVisitado();
while (!pilha.isEmpty()) {
Node v = pilha.peek();
System.out.println(pilha);
for(int i = 0; i <v.adjacencias.size(); i++){
Node adj = v.adjacencias.get(i);
if(adj.visitado == false){
System.out.println(v + " >> "+adj);
pilha.push(adj);
adj.setVisitado();
}
}
pilha.pop();
}
}
The graph I am trying to perform the search is this:
Iamusingasastructurealistoflistsfortheconstructionofthegraph.Theimpressionoftheedgesisasfollows:
A>>[B,C,D]B>>[A,E,C]C>>[A,B,D,F,G]D>>[A,C,G]E>>[B,F,H]F>>[C,E,I]G>>[D,C,J]H>>[E,I,L]I>>[F,H,L]J>>[G,I,L]L>>[H,I,J]
Theproblemis:apparentlythestackisonlyabletoreach/reachtheE
vertex.InitiallyIthoughtthatthereferencesofthearcscouldbewrong,buttheverticesarecorrectlyconnectedtoeachother.Theoutput,whenIprintonthescreenthestackisasfollows:
[A][A,B,C][A,B,C,F][A,B,C,F,E][A,B,C,F,E][A,B,C,F][A,B,C][A,B][A]
ThefunnythingisthatwhenIremovethepilha.pop();
aftertheloop,thecontentsofthestackistheresultofthelongestpath,butthecodegoesintoloop:
[A,B,C,D,G,J,I,L,H,E,F].
Nodeclassimplementation:
privatestaticclassNode{Stringvalor;ArrayList<Node>adjacencias;booleanvisitado;intmaiorSeq;NoderefMaxNextNode;charcolor;intdist;Nodepai;Node(Stringvalor){this.valor=valor;adjacencias=newArrayList<>();visitado=false;maiorSeq=0;refMaxNextNode=null;dist=0;}voidsetValor(Stringvalor){this.valor=valor;}booleanaddCaminho(NodeoutroNode){if(adjacencias.contains(outroNode)){returnfalse;}adjacencias.add(outroNode);returntrue;}voidsetVisitado(){this.visitado=true;}publicStringtoString(){return"" + valor;
}
public void pai() {
System.out.println("O pai de " + valor + " é: " + pai);
}
}