美文网首页计算机
Interview Question - Six Degrees

Interview Question - Six Degrees

作者: Richardo92 | 来源:发表于2016-09-28 07:07 被阅读2次

Question:
https://aaronice.gitbooks.io/lintcode/content/graph_search/six_degrees.html

My code:

public int sixDegrees(UndirectedGraphNode s, UndirectedGraphNode t) {
    Queue<UndirectedGraphNode> q = new LinkedList<UndirectedGraphNode>();
    Map<UndirectedGraphNode, Integer> map = new HashMap<UndirectedGraphNode, Integer>();
    q.offer(s);
    map.put(s, 0);
    
    while (!q.isEmpty()) {
        UndirectedGraphNode curr = q.poll();
        if (curr == t) {
            return map.get(curr) + 1;
        }
        for (UndirectedGraphNode next : curr.neighbors) {
            if (map.containsKey(next)) {
                continue;
            }
            q.offer(next);
            map.put(next, map.get(curr) + 1);
        }
    }
    return -1;
}

class UndirectedGraphNode {
    int label;
    List<UndirectedGraphNode> neighbors;
    UndirectedGraphNode(int x) {
        label = x;
        neighbors = new ArrayList<UndirectedGraphNode>();
    }
};

设计一个 HashMap 用来存到当前结点,需要的 step
也有做法是,拿一个更大的类把 GraphNode 包起来,同时包含一个step成员变量。表明到这个结点需要的step。

Anyway, Good luck, Richardo! -- 09/27/2016

相关文章

  • Interview Question - Six Degrees

    Question:https://aaronice.gitbooks.io/lintcode/content/gr...

  • 531. Six Degrees

    Description Six degrees of separation is the theory that ...

  • Linked: How everything is connec

    May-29-2017 Chapter 3: Six Degrees of Separation Six Degr...

  • interview question

    疑惑:1.script放在底部会影响dom渲染,不会影响解析是什么意思?解析的含义是浏览器读取文件,并构建dom树...

  • interview question

    写一个订阅发布模式 按照输出结果补全代码

  • interview question

    class方法与object_getClass方法有什么区别 实例Class方法直接返回object_getCla...

  • 6.4 六度空间

    1. 六度空间(Six Degrees of Separation) 2. 算法思路

  • 奥尼尔的六度分割理论

    原文链接:http://drunkevil.com/2015/06/14/six-degrees-of-shaqu...

  • LintCode 531 [Six Degrees]

    原题 六度分离是一个哲学问题,说的是每个人每个东西可以通过六步或者更少的步数建立联系。现在给你一个友谊关系,查询两...

  • 图论

    最短路 POJ 2139: Six Degrees of Cowvin Bacon直接上floyd即可,注意三重循...

网友评论

    本文标题:Interview Question - Six Degrees

    本文链接:https://www.haomeiwen.com/subject/hgshyttx.html