Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add DFS algorithm #92

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions Algorithms-using-java/DFS/DFS.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
public class DFS {
private static final int V = 8;

// Adjacency Matrix for a Sample Graph
private static final int[][] GRAPH = {
// A B C D E F G H
/* A */ {0, 1, 1, 1, 0, 0, 0, 0},
/* B */ {1, 0, 0, 0, 1, 1, 0, 0},
/* C */ {1, 0, 0, 1, 0, 0, 0, 0},
/* D */ {1, 0, 0, 1, 0, 0, 1, 0},
/* E */ {0, 1, 1, 1, 0, 0, 0, 1},
/* F */ {0, 1, 0, 0, 0, 0, 0, 1},
/* G */ {0, 0, 0, 1, 0, 0, 0, 1},
/* H */ {0, 0, 0, 0, 1, 1, 1, 0}
};
private static final int GRAPH_ROOT = 0;

// to keep track of visited node
private static final boolean[] VERTEX_VISITED = new boolean[V];

public static void DFS(int v) {

VERTEX_VISITED[v] = true;
System.out.println("Visited V" + v);

for (int u = 0; u < V; u++) {

// check for an edge between u and v
if (GRAPH[u][v] == 1) {
// check if this has been visited already
if (!VERTEX_VISITED[u]) {
DFS(u);
}
}
}
}

public static void main(String[] s) {

for (int v = 0; v < V; v++) {
// set all vertices to NOT_VISITED
VERTEX_VISITED[v] = false;
}

System.out.println("\nDFS Traversal ::\n");
DFS(GRAPH_ROOT);
}
}