3
I’m studying for a proof of algorithms and I ended up finding some problems to implement the DFS(Depht-First Search/deep search) using data structure 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’m trying to search is this:
I am using as a structure a list of lists for the construction of the graph. The impression of the edges is as follows:
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]
The problem is: apparently the stack is only getting to/from the vertex E
. Initially I thought that the references of the arcs could be wrong, but the vertices are correctly connected. The output, when I print on the screen the stack is as follows:
[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]
The funny thing is, when I remove the pilha.pop();
after the loop, the stack content is the result of the longest path, however the code enters loop:
[A, B, C, D, G, J, I, L, H, E, F].
Implementation of the Node class:
private static class Node {
String valor;
ArrayList<Node> adjacencias;
boolean visitado;
int maiorSeq;
Node refMaxNextNode;
char color;
int dist;
Node pai;
Node(String valor) {
this.valor = valor;
adjacencias = new ArrayList<>();
visitado = false;
maiorSeq = 0;
refMaxNextNode = null;
dist = 0;
}
void setValor(String valor) {
this.valor = valor;
}
boolean addCaminho(Node outroNode) {
if (adjacencias.contains(outroNode)) {
return false;
}
adjacencias.add(outroNode);
return true;
}
void setVisitado() {
this.visitado = true;
}
public String toString() {
return "" + valor;
}
public void pai() {
System.out.println("O pai de " + valor + " é: " + pai);
}
}
You can set the Node class definition?
– bruno
Added implementation :)
– Eduardo Silveira