Untitled
user_0781376
plain_text
12 days ago
1.9 kB
14
Indexable
import java.util.*; class Graph { private int vertices; private List<List<Integer>> adjList; public Graph(int vertices) { this.vertices = vertices; adjList = new ArrayList<>(); for (int i = 0; i < vertices; i++) { adjList.add(new ArrayList<>()); } } public void addEdge(int src, int dest) { adjList.get(src).add(dest); adjList.get(dest).add(src); // Undirected graph } public void dfs(int start) { boolean[] visited = new boolean[vertices]; System.out.print("DFS: "); dfsHelper(start, visited); System.out.println(); } private void dfsHelper(int node, boolean[] visited) { visited[node] = true; System.out.print(node + " "); for (int neighbor : adjList.get(node)) { if (!visited[neighbor]) { dfsHelper(neighbor, visited); } } } public void bfs(int start) { boolean[] visited = new boolean[vertices]; Queue<Integer> queue = new LinkedList<>(); queue.add(start); visited[start] = true; System.out.print("BFS: "); while (!queue.isEmpty()) { int node = queue.poll(); System.out.print(node + " "); for (int neighbor : adjList.get(node)) { if (!visited[neighbor]) { visited[neighbor] = true; queue.add(neighbor); } } } System.out.println(); } } public class Main { public static void main(String[] args) { Graph graph = new Graph(5); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 3); graph.addEdge(1, 4); graph.dfs(0); graph.bfs(0); } }
Editor is loading...
Leave a Comment