📖 Scenario: Imagine you have a map of cities connected by roads. You want to explore all cities starting from one city, going as deep as possible before backtracking. This is like exploring a maze by always going forward until you can't, then stepping back.
🎯 Goal: You will build a simple program that uses Depth First Search (DFS) to visit all cities in a graph starting from a given city. You will create the graph, set a starting city, write the DFS function, and print the order of visited cities.
📋 What You'll Learn
Create a graph as an adjacency list using a JavaScript object
Set a starting city for DFS
Write a DFS function that visits cities deeply using recursion
Print the order of cities visited by DFS
💡 Why This Matters
🌍 Real World
DFS is used in many real-world problems like maze solving, network analysis, and scheduling tasks where you need to explore all options deeply.
💼 Career
Understanding DFS is important for software engineers working with graphs, algorithms, and problem-solving in interviews and real projects.
Progress0 / 4 steps
1
Create the graph as an adjacency list
Create a JavaScript object called graph with these exact entries: 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [].
DSA Javascript
Hint
Use a JavaScript object with keys as city names and values as arrays of connected cities.
2
Set the starting city for DFS
Create a variable called startCity and set it to the string 'A'.
DSA Javascript
Hint
Just create a variable with the exact name and value.
3
Write the DFS function
Write a function called dfs that takes city and visited as parameters. Inside, add city to visited. Then use a for loop with variable neighbor to go through graph[city]. For each neighbor, if it is not in visited, call dfs(neighbor, visited) recursively.
DSA Javascript
Hint
Use recursion and a loop to visit neighbors deeply.
4
Print the order of visited cities
Create an empty array called visited. Call dfs(startCity, visited). Then print visited.join(' -> ') to show the order of cities visited.
DSA Javascript
Hint
Use an array to track visited cities and print them joined by arrows.
Practice
(1/5)
1. What does DFS (Depth First Search) do when traversing a graph?
easy
A. It only visits nodes connected directly to the start node.
B. It visits nodes level by level from the start node.
C. It explores as far as possible along each branch before backtracking.
D. It randomly visits nodes without any order.
Solution
Step 1: Understand DFS traversal
DFS explores a path deeply before moving to another path.
Step 2: Compare with other traversals
BFS visits nodes level by level, but DFS goes deep first.
Final Answer:
It explores as far as possible along each branch before backtracking. -> Option C
Quick Check:
DFS = deep exploration first [OK]
Hint: DFS goes deep first, BFS goes wide first [OK]
Common Mistakes:
Confusing DFS with BFS
Thinking DFS visits nodes randomly
Assuming DFS only visits direct neighbors
2. Which of the following is the correct way to start a DFS function in JavaScript for a graph represented as adjacency list graph?
easy
A. function dfs(node, visited = new Set()) {
B. function dfs(node, visited = []) {
C. function dfs(node, visited = {}) {
D. function dfs(node, visited = 0) {
Solution
Step 1: Identify suitable data structure for visited nodes
A Set is ideal to track visited nodes efficiently.
Step 2: Check function signature correctness
Using visited = new Set() initializes visited nodes properly.
Final Answer:
function dfs(node, visited = new Set()) { -> Option A
Quick Check:
Use Set for visited nodes [OK]
Hint: Use Set to track visited nodes in DFS [OK]
Common Mistakes:
Using array or object incorrectly for visited
Initializing visited as a number
Not initializing visited parameter
3. Given the graph adjacency list:
const graph = {
1: [2, 3],
2: [4],
3: [],
4: []
};
function dfs(node, visited = new Set()) {
visited.add(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
dfs(neighbor, visited);
}
}
return Array.from(visited);
}
console.log(dfs(1));
What is the output?
medium
A. [1, 3, 2, 4]
B. [1, 4, 2, 3]
C. [1, 2, 3, 4]
D. [1, 2, 4, 3]
Solution
Step 1: Start DFS from node 1
Visit 1, then neighbors 2 and 3 in order.
Step 2: Visit neighbors recursively
From 2, visit 4. From 3, no neighbors. Order: 1, 2, 4, 3.
Final Answer:
[1, 2, 4, 3] -> Option D
Quick Check:
DFS order = 1,2,4,3 [OK]
Hint: Follow neighbors deeply before next sibling [OK]
Common Mistakes:
Visiting neighbors in wrong order
Confusing BFS order with DFS
Not converting Set to array properly
4. Find the error in this DFS code snippet for graph traversal:
const graph = {
1: [2, 3],
2: [4],
3: [],
4: []
};
function dfs(node, visited = new Set()) {
visited.add(node);
for (const neighbor of graph[node]) {
if (visited.has(neighbor)) {
dfs(neighbor, visited);
}
}
return visited;
}
console.log(Array.from(dfs(1)));
medium
A. The condition should be if (!visited.has(neighbor)) instead of if (visited.has(neighbor))
B. The visited set should be an array instead
C. The graph object keys should be strings, not numbers
D. The function should return an array, not a set
Solution
Step 1: Check the neighbor visit condition
It incorrectly calls dfs if neighbor is already visited, causing infinite recursion.
Step 2: Correct the condition
Change to if (!visited.has(neighbor)) to visit unvisited neighbors only.
Final Answer:
The condition should be if (!visited.has(neighbor)) instead of if (visited.has(neighbor)) -> Option A
Quick Check:
Visit only unvisited neighbors [OK]
Hint: Call DFS only if neighbor not visited [OK]
Common Mistakes:
Calling DFS on already visited nodes
Using wrong data structure for visited
Returning wrong type from DFS
5. You want to find if there is a path from node 1 to node 5 in this graph:
const graph = {
1: [2, 3],
2: [4],
3: [5],
4: [],
5: []
};
function dfs(node, target, visited = new Set()) {
if (node === target) return true;
visited.add(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
if (dfs(neighbor, target, visited)) return true;
}
}
return false;
}
console.log(dfs(1, 5));
What will be the output and why?
hard
A. false, because the visited set is not updated correctly
B. true, because DFS finds a path 1 -> 3 -> 5
C. true, because DFS visits all nodes regardless of target
D. false, because node 5 is not directly connected to 1
Solution
Step 1: Check DFS path search logic
DFS returns true immediately when target node is found.
Step 2: Trace path from 1 to 5
Path exists: 1 -> 3 -> 5, so DFS returns true.
Final Answer:
true, because DFS finds a path 1 -> 3 -> 5 -> Option B
Quick Check:
DFS finds path = true [OK]
Hint: DFS returns true when target found [OK]
Common Mistakes:
Assuming direct connection needed
Ignoring early return on target found
Not updating visited set properly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.