avatar
s*n
1
This is an old G onsite question about one year back.
Find a connection between two people if there is one, or return false.
Everyone has father and mother and the connection means if there are any
common relatives.
My idea is as following:
The relative social network should be represented as graphs instead of
binary trees. One way to solve this problem is to use BFS. Specifically, we
can do BFS for person1 and person2 for their ancestors/descendants
simultaneously. We can use a hashtable to record every ancestor/descendant
that find along the BFS. If a common ancestor/descendant is found or person1
/person2 is found to be person2/person1’s ancestor/descendant, then they
have a connection. If they do not have any common ancestor/descendant, then
return false.
I was wondering if there is any better solution?
avatar
l*i
2
put an undirected edge from a person to his/her father, and one edge to the
mother. Then two persons are related iff there is a path from one person to
the other. You can do either bfs or dfs assume the graph is small enough.
Basically the connectivity problem.
avatar
b*d
3
maybe just a common ancestor means there is a connection also?
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。