Undirected Graph, BFS
directed graph BFS 里靠 indegree = 0 判断加入队列;
undirected graph BFS 里靠 degree = 0 判断加入队列;
论坛里看到的,非常赞的思路。 https://discuss.leetcode.com/topic/30572/share-some-thoughts
转换一下思路,我们做的事情其实非常近似于 Find Leaves of Binary Tree , 对于一个形状和链表一样的图,我们知道最优解一定是中点;对于一个 inorder traversal array,我们知道 height balanced tree 也一定以中点为 root;
因此,即使是 undirected graph,degree 也是非常重要的信息,只不过对于 undirected graph 来讲:
O(E + V)
public class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
int[] degrees = new int[n];
ArrayList[] graph = new ArrayList[n];
for(int i = 0; i < n; i++){
graph[i] = new ArrayList<>();
}
for(int[] edge : edges){
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
degrees[edge[0]]++;
degrees[edge[1]]++;
}
Queue<Integer> queue = new LinkedList<Integer>();
for(int i = 0; i < n; i++){
if(degrees[i] <= 1) queue.offer(i);
}
List<Integer> list = new ArrayList<>();
while(!queue.isEmpty()){
int size = queue.size();
list = new ArrayList<>();
for(int i = 0; i < size; i++){
int node = queue.poll();
list.add(node);
for(int j = 0; j < graph[node].size(); j++){
int next = (int)graph[node].get(j);
degrees[next] --;
if(degrees[next] == 1) queue.offer(next);
}
}
}
return list;
}
}BFS 做法,时间复杂度 O(E + V);
Last updated