DFS Backtracking with java
- by Cláudio Ribeiro
I'm having problems with DFS backtracking in an adjacency matrix. Here's my code:
(i added the test to the main in case someone wants to test it)
public class Graph {
private int numVertex;
private int numEdges;
private boolean[][] adj;
public Graph(int numVertex, int numEdges) {
this.numVertex = numVertex;
this.numEdges = numEdges;
this.adj = new boolean[numVertex][numVertex];
}
public void addEdge(int start, int end){
adj[start-1][end-1] = true;
adj[end-1][start-1] = true;
}
List<Integer> visited = new ArrayList<Integer>();
public Integer DFS(Graph G, int startVertex){
int i=0;
if(pilha.isEmpty())
pilha.push(startVertex);
for(i=1; i<G.numVertex; i++){
pilha.push(i);
if(G.adj[i-1][startVertex-1] != false){
G.adj[i-1][startVertex-1] = false;
G.adj[startVertex-1][i-1] = false;
DFS(G,i);
break;
}else{
visited.add(pilha.pop());
}
System.out.println("Stack: " + pilha);
}
return -1;
}
Stack<Integer> pilha = new Stack();
public static void main(String[] args) {
Graph g = new Graph(6, 9);
g.addEdge(1, 2);
g.addEdge(1, 5);
g.addEdge(2, 4);
g.addEdge(2, 5);
g.addEdge(2, 6);
g.addEdge(3, 4);
g.addEdge(3, 5);
g.addEdge(4, 5);
g.addEdge(6, 4);
g.DFS(g, 1);
}
}
I'm trying to solve the euler path problem. the program solves basic graphs but when it needs to backtrack, it just does not do it. I think the problem might be in the stack manipulations or in the recursive dfs call. I've tried a lot of things, but still can't seem to figure out why it does not backtrack. Can somebody help me ?