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

Added graph dfs #30

Closed
Closed
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
57 changes: 57 additions & 0 deletions Graph/dfs.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Graph {
private Map<Integer, List<Integer>> adjList;

// Constructor to initialize the graph
public Graph() {
adjList = new HashMap<>();
}

// Method to add an edge between two nodes (directed graph)
public void addEdge(int source, int destination) {
adjList.putIfAbsent(source, new ArrayList<>());
adjList.get(source).add(destination);
}

// DFS utility function
private void dfsUtil(int vertex, boolean[] visited) {
visited[vertex] = true;
System.out.print(vertex + " "); // Print the vertex as part of DFS traversal

// Visit all neighbors of the current vertex
List<Integer> neighbors = adjList.get(vertex);
if (neighbors != null) {
for (int neighbor : neighbors) {
if (!visited[neighbor]) {
dfsUtil(neighbor, visited);
}
}
}
}

// DFS traversal function
public void dfs(int startVertex) {
boolean[] visited = new boolean[adjList.size()];
System.out.println("DFS Traversal starting from vertex " + startVertex + ":");
dfsUtil(startVertex, visited);
}

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

// Add edges to the graph
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 0);
graph.addEdge(2, 3);
graph.addEdge(3, 3);

// Perform DFS starting from vertex 2
graph.dfs(2);
}
}
Loading