【Lintcode】531. Six Degrees

题目地址:

https://www.lintcode.com/problem/six-degrees/description

给定一个简单图,在给定图中的两个顶点,问这两个顶点之间的最短路径的长度。

思路是双向BFS。直接套用模板就可以了。代码如下:

import java.util.*;

public class Solution {
    /*
     * @param graph: a list of Undirected graph nodes
     * @param s: Undirected graph node
     * @param t: Undirected graph node
     * @return: an integer
     */
    public int sixDegrees(List<UndirectedGraphNode> graph, UndirectedGraphNode s, UndirectedGraphNode t) {
        // write your code here
        if (graph == null || graph.isEmpty()) {
            return -1;
        }
        // 如果两个点相等,直接返回0
        if (s == t) {
            return 0;
        }
        
        Queue<UndirectedGraphNode> beginQueue = new LinkedList<>();
        Queue<UndirectedGraphNode> endQueue = new LinkedList<>();
        Set<UndirectedGraphNode> beginSet = new HashSet<>();
        Set<UndirectedGraphNode> endSet = new HashSet<>();
        
        beginQueue.add(s);
        beginSet.add(s);
        endQueue.add(t);
        endSet.add(t);
        
        int step = 0;
        while (!beginQueue.isEmpty() && !endQueue.isEmpty()) {
            int beginSize = beginQueue.size(), endSize = endQueue.size();
            step++;
            for (int i = 0; i < beginSize; i++) {
                UndirectedGraphNode cur = beginQueue.poll();
                for (UndirectedGraphNode neighbor : cur.neighbors) {
                    if (endSet.contains(neighbor)) {
                        return step;
                    }
                    if (beginSet.add(neighbor)) {
                        beginQueue.offer(neighbor);
                    }
                }
            }
    
            step++;
            for (int i = 0; i < endSize; i++) {
                UndirectedGraphNode cur = endQueue.poll();
                for (UndirectedGraphNode neighbor : cur.neighbors) {
                    if (beginSet.contains(neighbor)) {
                        return step;
                    }
                    if (endSet.add(neighbor)) {
                        endQueue.offer(neighbor);
                    }
                }
            }
            
        }
        
        return -1;
    }
}

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

时空复杂度 O ( N + E ) O(N+E) O(N+E)

你可能感兴趣的:(#,DFS,BFS与图论,java,leetcode,算法,图论)