Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to decide whether two persons are connected

Here is the problem:

assuming two persons are registered in a social networking website, how to decide whether they are connected or not?

my analysis (after reading more): actually, the question is looking for - the shortest path from A to B in a graph. I think both BFS and Dijkstra's Algorithms works here and time complexity is exactly the same (O(V+E)) because it is an unweighted graph, so we can't take advantage of the priority queue. So, a simple queue could resolve the problem. But, both of them doesnt resolve the problem that: find the path between them.

Bidrectrol should be a better solution at this point.

like image 400
SecureFish Avatar asked Jul 02 '11 17:07

SecureFish


1 Answers

To find a path between the two, you should begin with a breadth first search. First find all neighbors of A, then find all neighbors of all neighbors of A, etc. Once B is hit, not only do you have a path from A to B, but you also have a shortest such path.

Dijkstra's algorithm rocks, and you may be able to speed this up by working from both end, i.e. find neighbors of A and neighbors of B, and compare.

If you do a depth first search, then you're following one path at a time. This will be much much slower.

like image 161
PengOne Avatar answered Oct 27 '22 18:10

PengOne