I’m implementing a DFS search to run in an adjacency matrix. With this i want to solve de euler path problem.
I already have DFS running with no problems, but now i want to modify it so it will perform backtrack whenever it tries to visit an edge that already has been visited.
Here’s my current code:
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+1][numVertex+1];
}
public void addEdge(int start, int end){
adj[start][end] = true;
adj[end][start] = true;
}
List<Integer> visited = new ArrayList<Integer>();
public Integer DFS(Graph G, int startVertex){
int i=0;
pilha.push(startVertex);
for(i=0; i<G.numVertex; i++){
if(G.adj[i][startVertex] != false){
System.out.println("i: " + i);
G.adj[i][startVertex] = false;
G.adj[startVertex][i] = false;
DFS(G, i);
pilha.push(i);
G.adj[i][startVertex] = true;
G.adj[startVertex][i] = true;
}
/* else{
pilha.pop();
}*/
if(!pilha.isEmpty()){
int c = pilha.pop();
visited.add(c);
System.out.println("visited: " + visited);
}
}
return -1;
}
Stack<Integer> pilha = new Stack();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numVertices = input.nextInt();
int numLinks = input.nextInt();
int startNode = input.nextInt();
Graph g = new Graph(numVertices, numLinks);
for(int i = 0; i<numLinks; i++){
g.addEdge(input.nextInt(),input.nextInt());
}
g.DFS(g, startNode);
}
}
The problem is, whenever i try to run the pop that is commented, i get an EmptyStackException. Any ideas on how to modify my code so it will backtrack when it tries to visit an edge that already has been visited.
Thx in advance.
That else of yours is getting executed if startvertex is not adjacent to some vertex i.
It really should get that else only if startvertex is not adjacent to any vertex i.
I’d do something like:
I’m not giving you a complete solution, but I think this solves your main logic problem.