Data Structures & AlgorithmsVery hardICPC regional · backtracking
Problem: How many simple paths go from 0 to 3 in the undirected graph with edges 0-1, 1-2, 2-3, 3-0 and the chord 0-2? Run the DFS code.
Problem: How many simple paths go from 0 to 3 in the undirected graph with edges 0-1, 1-2, 2-3, 3-0 and the chord 0-2? Run the DFS code.
g = {0: [1, 3, 2], 1: [0, 2], 2: [1, 3, 0], 3: [2, 0]}
def count(u, t, seen):
if u == t:
return 1
total = 0
for v in g[u]:
if v not in seen:
seen.add(v)
total += count(v, t, seen)
seen.remove(v)
return total
print(count(0, 3, {0}))What is printed?- A. 4
- B. 3
- C. 2
- D. 6
Correct answer: B. 3
The simple paths from 0 to 3 are 0-3, 0-2-3 and 0-1-2-3. Backtracking removes each visited vertex so no path repeats a vertex.
More Coding Interview Problems questions
- Problem: How many ordered pairs (a, b) with 1 <= a <= b <= 20 have gcd(a, b) = 1? Run the code. python from math import gcd print(sum(1…
- Problem: How many integers in [1, 100] are the product of exactly two distinct primes? Run the code. python def primesupto(n): s = [True]…
- Problem: What is the minimum length of a contiguous subarray of [1, 2, 3, 4, 5, 6, 7, 8] with sum at least 15? Run the two-pointer code…
- Problem: What is the integer floor of the square root of 10^12? Use binary search. python lo, hi = 0, 10 12 while lo < hi: mid = (lo + hi…
- Problem: Split [7, 2, 5, 10, 8] into 2 contiguous parts to minimise the largest part sum. What is the answer? Run the brute-force code…
- Problem: How many contiguous subarrays of [4, 1, -1, 2, 3] have a sum divisible by 4? Run the prefix-count code. python from collections…