Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start DFS from the given node.
DSA Go
func DFS(graph map[int][]int, start int, visited map[int]bool) {
visited[start] = true
for _, neighbor := range graph[start] {
if !visited[[1]] {
DFS(graph, neighbor, visited)
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'start' instead of 'neighbor' causes infinite recursion.
Checking 'visited' or 'graph' as keys causes errors.
✗ Incorrect
We check if the neighbor node has been visited before calling DFS recursively on it.
2fill in blank
mediumComplete the code to print nodes in DFS order.
DSA Go
func DFSPrint(graph map[int][]int, start int, visited map[int]bool) {
visited[start] = true
fmt.Println([1])
for _, neighbor := range graph[start] {
if !visited[neighbor] {
DFSPrint(graph, neighbor, visited)
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Printing 'neighbor' prints nodes multiple times.
Printing 'graph' or 'visited' causes errors.
✗ Incorrect
We print the current node 'start' before visiting neighbors to follow DFS order.
3fill in blank
hardFix the error in the DFS function to avoid revisiting nodes.
DSA Go
func DFS(graph map[int][]int, start int, visited map[int]bool) {
if visited[[1]] {
return
}
visited[start] = true
for _, neighbor := range graph[start] {
DFS(graph, neighbor, visited)
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'neighbor' causes infinite recursion.
Checking 'visited' or 'graph' causes errors.
✗ Incorrect
We check if the current node 'start' is already visited to stop recursion.
4fill in blank
hardFill both blanks to create a DFS function that returns the order of visited nodes.
DSA Go
func DFSOrder(graph map[int][]int, start int, visited map[int]bool, order *[]int) {
visited[[1]] = true
*order = append(*order, [2])
for _, neighbor := range graph[start] {
if !visited[neighbor] {
DFSOrder(graph, neighbor, visited, order)
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'neighbor' instead of 'start' causes wrong order.
Using 'visited' or 'graph' causes errors.
✗ Incorrect
Mark the current node 'start' as visited and append it to the order slice.
5fill in blank
hardFill all three blanks to implement DFS that counts connected components in a graph.
DSA Go
func CountComponents(graph map[int][]int) int {
visited := make(map[int]bool)
count := 0
for node := range graph {
if !visited[[1]] {
DFSCount(graph, [2], visited)
count[3]
}
}
return count
}
func DFSCount(graph map[int][]int, start int, visited map[int]bool) {
visited[start] = true
for _, neighbor := range graph[start] {
if !visited[neighbor] {
DFSCount(graph, neighbor, visited)
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'start' instead of 'node' in the loop causes errors.
Using '+=' instead of '++' changes count incorrectly.
✗ Incorrect
Check if 'node' is visited, call DFSCount on 'node', then increment count by 1.
