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 q = new LinkedList();
    Map map = new HashMap();
    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 neighbors;
    UndirectedGraphNode(int x) {
        label = x;
        neighbors = new ArrayList();
    }
};

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

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

你可能感兴趣的:(Interview Question - Six Degrees)