Reputation: 61
I'm having problems with geting my DFS to work properly. The graph is conected like this:
0 --> 1
0 --> 5
5 --> 4
4 --> 3
4 --> 2
2 --> 3
2 --> 0
3 --> 2
3 --> 5
So the outcome after I run it through my DFS should be:
0,1,5,4,2,3
but I'm getting
0,1,5,2,3,4
heres the code:
package kth.id2010.lab.lab05;
public class DFS {
static void dfs(int edges[][], int vertex, boolean[] visited){
visited[vertex] = true;
for(int i = vertex + 1; i < edges[vertex].length; i++){
if(edges[vertex][i] == 1 && !visited[i]){
dfs(edges,i,visited);
}
}
}
public static void main(String[] args){
int n = 6;
int[][] edges = new int[n][n];
boolean[] visited = new boolean[n];
//Vertex nr: 0
edges[0][0] = 0;
edges[0][1] = 1; //0 --> 1
edges[0][2] = 0;
edges[0][3] = 0;
edges[0][4] = 0;
edges[0][5] = 1; //0 --> 5
//Vertex nr: 1
edges[1][0] = 0;
edges[1][1] = 0;
edges[1][2] = 0;
edges[1][3] = 0;
edges[1][4] = 0;
edges[1][5] = 0;
//Vertex nr: 2
edges[2][0] = 1; //2 --> 0
edges[2][1] = 0;
edges[2][2] = 0;
edges[2][3] = 1; //2 --> 3
edges[2][4] = 0;
edges[2][5] = 0;
//Vertex nr: 3
edges[3][0] = 0;
edges[3][1] = 0;
edges[3][2] = 1; //3 --> 2
edges[3][3] = 0;
edges[3][4] = 0;
edges[3][5] = 1; //3 --> 5
//Vertex nr: 4
edges[4][0] = 0;
edges[4][1] = 0;
edges[4][2] = 1; //4 --> 2
edges[4][3] = 1; //4 --> 3
edges[4][4] = 0;
edges[4][5] = 0;
//Vertex nr: 5
edges[5][0] = 0;
edges[5][1] = 0;
edges[5][2] = 0;
edges[5][3] = 0;
edges[5][4] = 1; //5 --> 4
edges[5][5] = 0;
for(int i = 0; i <n; i++){
visited[i] = false;
}
for(int i = 0; i <n; i++){
if(visited[i] == false){
dfs(edges,i,visited);
}
}
}
}
I can't really figure out why it stops working after the 3 time.
Upvotes: 0
Views: 934
Reputation: 873
The thing I noticed is that you start with i = vertex+i, therefore after you reached vertex 5 it will return to the main method where we entered from with vertex 0, and continue with vertex 2 and not vertex 4 as expected. So change the following line:
static void dfs(int edges[][], int vertex, boolean[] visited){
visited[vertex] = true;
for(int i = vertex + 1; i < edges[vertex].length; i++){
...
to:
for(int i = 0; i < edges[vertex].length; i++){
Upvotes: 2