Discover how a simple rule can help you explore any maze or network without getting lost!
Why DFS Depth First Search on Graph in DSA C#?
Imagine you have a big maze with many paths and rooms. You want to find if there is a way to get from the start to a treasure hidden somewhere. If you try to remember every path you took manually, it becomes confusing and you might get lost or repeat the same paths again and again.
Trying to explore every path by guessing or writing down every step on paper is slow and easy to mess up. You might forget which rooms you already checked, or waste time going back and forth. This makes finding the treasure very frustrating and error-prone.
Depth First Search (DFS) helps by exploring one path deeply before backtracking. It uses a simple rule: go as far as you can down one path, then come back and try another. This way, you never lose track of where you are, and you systematically check all possible paths without repeating.
bool FindPath(int current, int target, List<int>[] graph, HashSet<int> visited) {
visited.Add(current);
if (current == target) return true;
foreach (int neighbor in graph[current]) {
if (!visited.Contains(neighbor)) {
if (FindPath(neighbor, target, graph, visited)) return true;
}
}
return false;
}void DFS(int node, List<int>[] graph, bool[] visited) {
visited[node] = true;
foreach (int neighbor in graph[node]) {
if (!visited[neighbor]) {
DFS(neighbor, graph, visited);
}
}
}DFS enables you to explore complex networks or mazes efficiently and systematically, ensuring no path is missed or repeated unnecessarily.
Social networks use DFS to find all friends connected to you by following friend links deeply, helping suggest new friends or find communities.
Manual path exploration is confusing and slow.
DFS explores deeply and backtracks systematically.
It helps check all paths without repetition or getting lost.
Practice
Depth First Search (DFS) on a graph?Solution
Step 1: Understand DFS traversal
DFS explores a graph by going deep into one branch before backtracking to explore others.Step 2: Compare with other traversal methods
BFS visits neighbors first, but DFS goes deep first.Final Answer:
Explore as far as possible along each branch before backtracking -> Option CQuick Check:
DFS = deep exploration first [OK]
- Confusing DFS with BFS
- Thinking DFS visits neighbors first
- Assuming DFS visits nodes by distance
Dictionary<int, List<int>> graph?Solution
Step 1: Check parameters and visited tracking
void DFS(int node, HashSet<int> visited) { if (visited.Contains(node)) return; visited.Add(node); foreach (var neighbor in graph[node]) DFS(neighbor, visited); } uses HashSet to track visited nodes and prevents revisiting.Step 2: Verify iteration over neighbors
void DFS(int node, HashSet<int> visited) { if (visited.Contains(node)) return; visited.Add(node); foreach (var neighbor in graph[node]) DFS(neighbor, visited); } correctly iterates over neighbors of the current node from the graph dictionary.Final Answer:
void DFS(int node, HashSet<int> visited) { if (visited.Contains(node)) return; visited.Add(node); foreach (var neighbor in graph[node]) DFS(neighbor, visited); } -> Option AQuick Check:
Correct recursion with visited check [OK]
- Not checking if node is visited before recursion
- Using List instead of HashSet for visited (slow lookup)
- Iterating over graph keys instead of neighbors
var graph = new Dictionary {
{1, new List<int>{2, 3}},
{2, new List<int>{4}},
{3, new List<int>{4}},
{4, new List<int>()}
};
List<int> visited = new List<int>();
DFS(1, visited); // DFS as defined in option C above
Console.WriteLine(string.Join(", ", visited));What is the output?
Solution
Step 1: Start DFS from node 1
Visit 1, mark visited. Neighbors: 2, 3.Step 2: Visit neighbor 2 first
Visit 2, then its neighbor 4. 4 has no neighbors, backtrack.Step 3: Backtrack to 1 and visit neighbor 3
Visit 3, then neighbor 4 (already visited, skip).Step 4: Order of visited nodes
Visited nodes in order: 1, 2, 4, 3.Final Answer:
1, 2, 4, 3 -> Option BQuick Check:
DFS order = 1,2,4,3 [OK]
- Assuming BFS order instead of DFS
- Visiting node 3 before node 2
- Revisiting already visited nodes
void DFS(int node, HashSet<int> visited) {
visited.Add(node);
foreach (var neighbor in graph.Keys) {
if (!visited.Contains(neighbor)) {
DFS(neighbor, visited);
}
}
}What is the main problem with this DFS implementation?
Solution
Step 1: Analyze the foreach loop
The loop iterates over all keys in the graph, not neighbors of the current node.Step 2: Understand DFS neighbor traversal
DFS should explore neighbors of the current node, not all nodes in the graph.Final Answer:
It iterates over all graph nodes instead of neighbors of the current node -> Option AQuick Check:
DFS must visit neighbors, not all nodes [OK]
- Looping over graph.Keys instead of graph[node]
- Forgetting to add node to visited
- Not checking visited before recursion
var graph = new Dictionary {
{1, new List<int>{2, 3}},
{2, new List<int>{4}},
{3, new List<int>{4, 5}},
{4, new List<int>{}},
{5, new List<int>{}}
};
bool DFS(int current, int target, HashSet<int> visited) {
if (current == target) return true;
visited.Add(current);
foreach (var neighbor in graph[current]) {
if (!visited.Contains(neighbor)) {
if (DFS(neighbor, target, visited)) return true;
}
}
return false;
}
var visited = new HashSet<int>();
bool result = DFS(1, 5, visited);
Console.WriteLine(result);What will be printed?
Solution
Step 1: Start DFS from node 1 looking for 5
Visit 1, neighbors 2 and 3.Step 2: Explore neighbor 2
From 2, visit 4. 4 has no neighbors, backtrack.Step 3: Explore neighbor 3
From 3, neighbors are 4 and 5. 4 visited, then 5 found matches target.Step 4: DFS returns true when target found
DFS returns true and prints True.Final Answer:
True -> Option DQuick Check:
Path exists from 1 to 5 [OK]
- Assuming no path because 5 is not direct neighbor
- Not returning true when target found
- Forgetting to mark visited nodes
Ready to prove it?
Pass the test and this pattern moves unknown
