Six Degrees

Six degrees of separation is the theory that everyone and everything is six or fewer steps away, by way of introduction, from any other person in the world, so that a chain of "a friend of a friend" statements can be made to connect any two people in a maximum of six steps.

Given a friendship relations, find the degrees of two people, return -1 if they can not been connected by friends of friends.

Example
Gien a graph:

1------2-----4
  \             /
    \         /
     \--3--/
{1,2,3#2,1,4#3,1,4#4,2,3} and s = 1, t = 4 return 2

Gien a graph:

1 2-----4
          /
        /
      3
{1#2,4#3,4#4,2,3} and s = 1, t = 4 return -1

这道题的degreeFromSource不仅用来记录节点到source的距离,同时也可以用来记录是否访问。因为无向图里计算某个节点到source的距离只需要访问一次,不能重复计算。

/**
 * Definition for Undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { 
 *         label = x;
 *         neighbors = new ArrayList<UndirectedGraphNode>(); 
 *     }
 * };
 */
public class Solution {
    /**
     * @param graph a list of Undirected graph node
     * @param s, t two Undirected graph nodes
     * @return an integer
     */
    public int sixDegrees(List<UndirectedGraphNode> graph,
                          UndirectedGraphNode s,
                          UndirectedGraphNode t) {
        // Write your code here
        if (graph == null || s == t || graph.size() == 0){
            return 0;
        }
        Map<UndirectedGraphNode, Integer> degreeFromSource = new HashMap<>();
        Queue<UndirectedGraphNode> queue = new LinkedList<>();
        degreeFromSource.put(s,0);
        queue.offer(s);
        while (!queue.isEmpty()){
            UndirectedGraphNode curt = queue.poll();
            for (UndirectedGraphNode nei : curt.neighbors){
                if (degreeFromSource.containsKey(nei)){
                    continue;
                }
                degreeFromSource.put(nei, degreeFromSource.get(curt) + 1);
                if (nei == t){
                    return degreeFromSource.get(curt) + 1;
                }
                queue.offer(nei);
            }
        }
        return -1;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容