I was working on this puzzle from HackerRank, "repairing-roads"
The country of Byteland contains cities and bidirectional roads. There is a path between any two cities. The roads in Byteland were built long ago, and now they are in need of repair. You have been hired to fix all the roads. You intend to do this by dispatching robots on some of the roads. Each robot will repair the road he is currently on and then moves to one of the adjacent unrepaired roads. After repairing that, it will move to another adjacent unrepaired road, repair that and so on.
Two roads are adjacent if they have the same city at one of their endpoints. For the process to be efficient, no two robots will ever repair the same road, and no road can be visited twice. What is the minimum number of robots needed to accomplish the task?
Input Format
The first line contains the number of test cases T. T test cases follow. The first line of each test case contains N, the number of cities in Byteland. The cities are numbered 0..N-1. The following N-1 lines contain the description of the roads. The ith line contains two integers a and b, meaning that there is a road connecting cities with numbers ai and bi.
Conceptually the way to solve this problem is via Depth-First-Search, but I have questions regarding how DFS is used exactly to solve this problem. I tried a few ways and could not get it to work.
If we model the input data as a graph and execute DFS, we would get as expected, the depth-first traversal path. Then we could prevent the search from going backwards, and find the number of distinct paths from remaining vertices (either using visited flags or deleting the vertex). But this doesn't give the optimum solution, i.e minimum number of robots, as I cannot control the choices when there are multiple vertices to a node.
I found some solutions where they model it as a tree, and using some kind of recursion to track how many levels get traversed when a leaf node is reached, as the recursion stack returns to the node. Using that they track the number of robots by doing lvl / 2. I'm not sure whether this conforms to some algorithm but I've no clue how it was used to solve the problem.
def dfs(n):
visited[n] = True
r, l1, l2 = 0, 0, 0
for adj in G[n]:
if visited[adj]: continue
r1, l = dfs(adj)
r += r1
if l == 1: l1 += 1
if l == 2: l2 += 1
if l2 == 0:
if l1 == 0:
return r, 1
else:
return r, 2
else:
if l2 % 2 == 0:
return r + l2//2, 0
else:
return r + l2//2, 2}