-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathDFSTraversal.java
More file actions
84 lines (61 loc) · 2.37 KB
/
Copy pathDFSTraversal.java
File metadata and controls
84 lines (61 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* Algorithm Name
DFS (Depth First Search Traversal)
Programming Language
Java
Category
Traversing / Searching
Difficulty Level
Easy
* Algorithm Description :
1. Problem it solves:
-> Used for graph traversal and can be applied for topological sorting, cycle detection, and pathfinding problems.
2. Approach / Idea:
-> DFS uses a stack (can be implemented recursively or iteratively) and explores nodes as deep as possible before backtracking.
-> Start from the source node and mark it as visited.
-> Visit all unvisited neighbors recursively (or using a stack).
-> Continue until all reachable nodes are visited.
3. Complexity:
Time: O(V + E), where V = number of vertices and E = number of edges.
Space: O(V) for the recursion stack or explicit stack and visited set/array.
* Author : Subhodeep Chatterjee
*/
import java.util.*;
public class DFSTraversal {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input vertices and edges
System.out.print("Enter number of vertices: ");
int V = sc.nextInt();
System.out.print("Enter number of edges: ");
int E = sc.nextInt();
// Graph as adjacency list
Map<Integer, List<Integer>> graph = new HashMap<>();
System.out.println("Enter edges (u v): ");
for (int i = 0; i < E; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
addEdge(graph, u, v); // undirected edge
}
System.out.print("Enter starting node: ");
int start = sc.nextInt();
System.out.println("DFS Traversal:");
Set<Integer> visited = new HashSet<>();
dfs(graph, start, visited);
}
// Function to add edge (undirected graph)
static void addEdge(Map<Integer, List<Integer>> graph, int u, int v) {
graph.computeIfAbsent(u, k -> new ArrayList<>()).add(v);
// avoid the given below line if you want directed graph
graph.computeIfAbsent(v, k -> new ArrayList<>()).add(u);
}
// Recursive DFS Function
static void dfs(Map<Integer, List<Integer>> graph, int node, Set<Integer> visited) {
visited.add(node);
System.out.print(node + " ");
for (int neighbour : graph.getOrDefault(node, new ArrayList<>())) {
if (!visited.contains(neighbour)) {
dfs(graph, neighbour, visited);
}
}
}
}