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

Create dfs.java #1

Merged
merged 1 commit into from
Oct 21, 2024
Merged
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
47 changes: 47 additions & 0 deletions javaAlgo/dfs.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import java.util.LinkedList;

public class GraphDFS {
private LinkedList<Integer>[] adjLists;
private boolean[] visited;

// Graph Constructor
GraphDFS(int vertices) {
adjLists = new LinkedList[vertices];
visited = new boolean[vertices];

for (int i = 0; i < vertices; i++) {
adjLists[i] = new LinkedList<>();
}
}

// Add an edge to the graph
void addEdge(int src, int dest) {
adjLists[src].add(dest);
}

// DFS traversal of the vertices reachable from v
void DFS(int vertex) {
visited[vertex] = true;
System.out.print(vertex + " ");

for (int adj : adjLists[vertex]) {
if (!visited[adj]) {
DFS(adj);
}
}
}

public static void main(String[] args) {
GraphDFS graph = new GraphDFS(4);

graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 0);
graph.addEdge(2, 3);
graph.addEdge(3, 3);

System.out.println("Depth First Search starting from vertex 2:");
graph.DFS(2);
}
}