拓扑排序的BFS做法
来源:互联网 发布:价值投资数据类app 编辑:程序博客网 时间:2024/05/16 01:16
无论是 directed 还是 undirected Graph,其 BFS 的核心都在于 "indegree",处理顺序也是从indegree 最小的开始。
1) 先用一个 HashMap 统计下所有节点的 indegree;
(值越高的,在拓扑排序中位置也就越靠后,因为还有 N = current indegree 的 parent node 们没有处理完。)
2) 因此在循环最开始,我们把所有 indegree = 0作为(均不在 hashmap中) (1)BFS 的起点(进queue) (2)加到 list 中。
3) 在 BFS 过程中,我们依次取出队列里 node 的 neighbors,并把他们的 indegree减去1,代表其 parent node 已经被处理完,有效 indegree 减少。
4) 当减去1之后node 的 indegree 已经是 0(1)BFS 的起点(进queue) (2)加到 list 中。
public class Solution {
/**
* @param graph: A list of Directed graph node
* @return: Any topological order for the given graph.
*/
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
// write your code here
ArrayList<DirectedGraphNode> list = new ArrayList<DirectedGraphNode>();
// Key : node
// Value : current in-degree count
HashMap<DirectedGraphNode, Integer> map = new HashMap<>();
for(DirectedGraphNode node : graph){
for(DirectedGraphNode neighbor : node.neighbors){
if(!map.containsKey(neighbor)){
map.put(neighbor, 1);
} else {
map.put(neighbor, map.get(neighbor) + 1);
}
}
}
// Now we know each node's in-degree (out is trivial)
Queue<DirectedGraphNode> queue = new LinkedList<>();
Iterator<DirectedGraphNode> iter = graph.iterator();
while(iter.hasNext()){
DirectedGraphNode node = iter.next();
// get all nodes without indegree
if(!map.containsKey(node)){
queue.offer(node);
list.add(node);
}
}
while(!queue.isEmpty()){
DirectedGraphNode node = queue.poll();
for(DirectedGraphNode next : node.neighbors){
// node "next"'s parent has been processed
map.put(next, map.get(next) - 1);
if(map.get(next) == 0){
list.add(next);
queue.offer(next);
}
}
}
return list;
}
}
- 拓扑排序的BFS做法
- 拓扑排序的bfs算法
- 拓扑排序DFS做法
- 拓扑排序的DFS和BFS
- BFS和DFS下的拓扑排序
- 拓扑排序+BFS+vector的使用
- hdu 2647 bfs+拓扑排序
- 【拓扑排序】BFS 别犯傻
- UVA1423Guess (dfs,bfs拓扑排序)
- 22.4-5拓扑排序BFS
- 拓扑排序(BFS,DFS)
- TopSort(拓扑排序)中DFS和BFS的应用
- UVa 10285 BFS的做法
- 算法导论--BFS、DFS及拓扑排序
- 【hdu 2647】 【拓扑排序 BFS】Reward
- 图—拓扑排序(BFS)
- 拓扑排序-bfs-广度优先搜索
- HDOJ 3342 Legal or Not(拓扑排序)队列做法和DFS做法
- INSTALL_PARSE_FAILED_MANIFEST_MALFORMED问题的解决
- RecyclerView加载网络图片防止图片错乱问题
- 【u118】日志分析
- React Native
- 使用MyEclipse开发HBase应用程序
- 拓扑排序的BFS做法
- Regional 2014 - Asia Mudanjiang - F Fiber-optic Network
- .tbd和.dylib
- 如何获得领导赏识
- Caffe: 安装Caffe的最快捷方法
- BUCK电路分析
- udacity assignment1
- Ubuntu GSL科学计算库安装配置
- 【u121】教主的花园