Блог пользователя jankit366

Автор jankit366, история, 19 месяцев назад, По-английски

A and B wants to reach some destination in an undirected graph using the least number of unique edges. Find the count of unique edges.

Let's say the two paths come out to be this.. A-x-y-D B-y-D

Output : 4

Explanation : A-x, x-y, y-D and B-y

Follow up: What if there are multiple sources?

Can someone help me to solve this optimally?

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
19 месяцев назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

Do a BFS from nodes A, B and D, now you know the distance from A, B and D to every node. There are two cases:
1) the paths A — D and B — D don't intersect
2) the paths meet at some node X(A — X — D and B — X — D)

the first case is just $$$d_{DA} + d_{DB}$$$
in the second case to find the node X we can just try for every node $$$d_{AX} + d_{BX} + d_{DX}$$$