拓扑排序(BFS,DFS)
来源:互联网 发布:java论坛哪个好 编辑:程序博客网 时间:2024/05/16 09:26
我们用两种方法来做这道题。
BFS
宽度优先搜索,是说我们每次把没有父亲节点的节点打印。具体操作可以是计算所有节点的入度。将入度为0的节点输出,同时将输出节点的儿子的入度减去一。我们用队列维持入度为0的节点集合。
/** * Definition for Directed graph. * struct DirectedGraphNode { * int label; * vector<DirectedGraphNode *> neighbors; * DirectedGraphNode(int x) : label(x) {}; * }; */class Solution {public: /** * @param graph: A list of Directed graph node * @return: Any topological order for the given graph. */ vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) { // write your code here vector<int> indegree(graph.size(),0); for(auto node:graph){ for(int i = 0; i < node->neighbors.size(); ++i){ indegree[node->neighbors[i]->label]++; } } queue<DirectedGraphNode*> que; for(int i = 0; i < indegree.size(); ++i){ if(indegree[i] == 0) que.push(graph[i]); } vector<DirectedGraphNode *> res; while(!que.empty()){ DirectedGraphNode *temp = que.front(); for(auto pi:temp->neighbors){ indegree[pi->label]--; if(indegree[pi->label] == 0) que.push(graph[pi->label]); } que.pop(); res.push_back(temp); } return res; }};
DFS
深度优先搜索则是一旦我们要输出一个节点,则把它的父亲全部输出即可。考虑到我们的数据结构是记录每个节点的儿子节点,所以我们这样考虑:
一旦要输出一个节点,先把儿子节点全部输出;最后reverse即可。
创建childinres布尔数组是为了查询O(1)。《—–感谢roommate
/** * Definition for Directed graph. * struct DirectedGraphNode { * int label; * vector<DirectedGraphNode *> neighbors; * DirectedGraphNode(int x) : label(x) {}; * }; */class Solution {public: /** * @param graph: A list of Directed graph node * @return: Any topological order for the given graph. */ void dfs(vector<DirectedGraphNode*> &res, vector<DirectedGraphNode*>& graph, int target, vector<bool>& targetinres){ if(targetinres[target]) return; //cout<<target<<endl; for(auto node:graph[target]->neighbors) dfs(res,graph,node->label,targetinres); res.push_back(graph[target]); targetinres[target] = true; } vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) { // write your code here vector<DirectedGraphNode*> res; vector<bool> targetinres(graph.size(),false); for(int i = 0; i < graph.size(); ++i){ dfs(res,graph,i,targetinres); } reverse(res.begin(),res.end()); return res; }};
阅读全文
0 0
- 拓扑排序(BFS,DFS)
- UVA1423Guess (dfs,bfs拓扑排序)
- 算法导论--BFS、DFS及拓扑排序
- 拓扑排序的DFS和BFS
- BFS和DFS下的拓扑排序
- 拓扑排序+DFS(POJ1270)
- uva10305(拓扑排序dfs)
- hdu5438(拓扑排序+dfs)
- 算法学习笔记(一):拓扑排序与传递闭包(通过bfs&&dfs)
- 图的邻接表的遍历(DFS(递归,非递归),BFS,拓扑排序)
- 图的遍历(dfs、bfs、最短路、最小生成树、拓扑排序)
- TopSort(拓扑排序)中DFS和BFS的应用
- [数据结构]Graph之拓扑排序BFS&DFS实现
- 图—拓扑排序(BFS)
- uva 10305 拓扑排序(五种方式实现,全面理解邻接表+BFS实现+DFS实现)
- uva 196 Spreadsheet(拓扑排序+DFS)
- poj1270Following Orders(拓扑排序+dfs回溯)
- 拓扑排序(topological sort)DFS
- codevs 2913 建筑抢修
- iOS应用架构现状分析
- Appcan+vue+vux+webpack开发app(原创)
- 【Linux】中的进程信号三张表
- 6月28
- 拓扑排序(BFS,DFS)
- 自我学习的网站
- JS模块化
- 光源的选择
- HDU 6024 Building Shops (简单dp)
- 连续子数组的最大和
- 路由及交换机设置上网的几种方式
- angularJS搭建环境
- 6月29