0% found this document useful (0 votes)
7 views2 pages

Java Graph BFS and DFS Example

The document contains a Java program that implements a graph data structure with methods for adding undirected edges and performing breadth-first search (BFS) and depth-first search (DFS) traversals. The main method creates a graph with 5 vertices, adds edges, and demonstrates both traversal methods starting from vertex 0. The output displays the order of node visits for both BFS and DFS.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Java Graph BFS and DFS Example

The document contains a Java program that implements a graph data structure with methods for adding undirected edges and performing breadth-first search (BFS) and depth-first search (DFS) traversals. The main method creates a graph with 5 vertices, adds edges, and demonstrates both traversal methods starting from vertex 0. The output displays the order of node visits for both BFS and DFS.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import [Link].

*;

public class Main {

static class Graph {


private int V;
private List<List<Integer>> adj;

Graph(int V) {
this.V = V;
adj = new ArrayList<>();

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


[Link](new ArrayList<>());
}
}

// Undirected edge
void addEdge(int u, int v) {
[Link](u).add(v);
[Link](v).add(u);
}

// BFS traversal
void bfs(int start) {
boolean[] visited = new boolean[V];
Queue<Integer> queue = new LinkedList<>();

visited[start] = true;
[Link](start);

while (![Link]()) {
int node = [Link]();
[Link](node + " ");

for (int neighbour : [Link](node)) {


if (!visited[neighbour]) {
visited[neighbour] = true;
[Link](neighbour);
}
}
}
}
// DFS traversal (recursive)
void dfs(int start) {
boolean[] visited = new boolean[V];
dfsHelper(start, visited);
}

void dfsHelper(int node, boolean[] visited) {


visited[node] = true;
[Link](node + " ");

for (int neighbour : [Link](node)) {


if (!visited[neighbour]) {
dfsHelper(neighbour, visited);
}
}
}
}

public static void main(String[] args) {

Graph g = new Graph(5);

[Link](0, 1);
[Link](0, 2);
[Link](1, 3);
[Link](2, 4);

[Link]("BFS Traversal: ");


[Link](0);

[Link]("\nDFS Traversal: ");


[Link](0);
}
}

You might also like