Data Structures & AlgorithmsModerateTCS NQT · graph warm-up
Problem: Count the connected components of the undirected graph on 6 vertices with edges (0,1), (1,2), (3,4), (5,5) using DFS. Run the code.
Problem: Count the connected components of the undirected graph on 6 vertices with edges (0,1), (1,2), (3,4), (5,5) using DFS. Run the code.
g = {i: [] for i in range(6)}
for u, v in [(0, 1), (1, 2), (3, 4), (5, 5)]:
g[u].append(v)
g[v].append(u)
seen = set()
comp = 0
def dfs(u):
seen.add(u)
for v in g[u]:
if v not in seen:
dfs(v)
for i in range(6):
if i not in seen:
comp += 1
dfs(i)
print(comp)What is printed?- A. 4
- B. 3
- C. 5
- D. 6
Correct answer: B. 3
The components are {0,1,2}, {3,4} and {5}, so there are 3. The self-loop (5,5) does not join anything, and forgetting the isolated vertex 5 gives 2.
More Coding Interview Problems questions
- Problem: Check whether the directed graph with edges 0->1, 1->2, 2->0, 2->3 contains a cycle using Kahn's algorithm (count the nodes that…
- Problem: Find the minimum cost to reach node 3 from node 0 using at most 2 edges in the directed graph with edges (0,1,5), (1,3,5)…
- Problem: Count the nodes at depth exactly 2 in the rooted tree with children 0: [1, 2], 1: [3], 2: [4, 5], 3: [], 4: [], 5: []. Root 0 has…
- Problem: How many integers from 1 to 1000 are divisible by 3 or by 5 but not by both?
- Problem: What is the product of the distinct prime factors of 360? Run the code. python n = 360 p, prod = 2, 1 while p p <= n: if n % p ==…
- Problem: What is the sum of all primes up to 50? Run the code. python print(sum(p for p in range(2, 51) if all(p % d for d in range(2…