Interview Question - Six Degrees

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

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/ab7af378461a#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞