import java.util.*;
class Graph {
private int V; // Number of vertices
private LinkedList<Integer>[] adjList; // Adjacency list representation
public Graph(int V) {
this.V = V;
adjList = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjList[i] = new LinkedList<>();
}
}
// Add an edge to the graph
public void addEdge(int v, int w) {
adjList[v].add(w);
adjList[w].add(v); // For undirected graphs
}
// Depth-First Search (DFS)
public void dfs(int startVertex) {
boolean[] visited = new boolean[V];
dfsRecursive(startVertex, visited);
}
private void dfsRecursive(int vertex, boolean[] visited) {
visited[vertex] = true;
System.out.print(vertex + " ");
for (int neighbor : adjList[vertex]) {
if (!visited[neighbor]) {
dfsRecursive(neighbor, visited);
}
}
}
// Breadth-First Search (BFS)
public void bfs(int startVertex) {
boolean[] visited = new boolean[V];
Queue<Integer> queue = new LinkedList<>();
visited[startVertex] = true;
queue.add(startVertex);
while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");
for (int neighbor : adjList[vertex]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);
}
}
}
}
}
public class Main {
public static void main(String[] args) {
Graph graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
graph.addEdge(3, 5);
System.out.println("Depth-First Search (DFS):");
graph.dfs(0); // Start DFS from vertex 0
System.out.println();
System.out.println("\nBreadth-First Search (BFS):");
graph.bfs(0); // Start BFS from vertex 0
}
}
0 Comments