LintCode "Route Between Two Nodes in Graph"
2015-09-24 05:14
676 查看
DFS ended up with TLE. Only BFS works.
View Code
/** * 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 * @param s: the starting Directed graph node * @param t: the terminal Directed graph node * @return: a boolean value */ bool bfs(DirectedGraphNode*s, DirectedGraphNode* t) { unordered_set<DirectedGraphNode*> visited; queue<DirectedGraphNode*> q; q.push(s); while(!q.empty()) { auto pt = q.front(); q.pop(); if(pt->label == t->label) return true; visited.insert(pt); for(auto c : pt->neighbors) { if(visited.find(c) == visited.end()) q.push(c); } } return false; } bool hasRoute(vector<DirectedGraphNode*> graph, DirectedGraphNode* s, DirectedGraphNode* t) { unordered_set<DirectedGraphNode*> visiteds; visiteds.insert(s); bool b1 = bfs(s, t); if(b1) return true; visiteds.clear(); visiteds.insert(t); return bfs(s, t); } };
View Code
相关文章推荐
- nodejs抓取别人家的页面的始末
- Node-red catch节点
- nodejs、npm、grunt——名词解释
- node.js基础教程
- LeetCode(49) Populating Next Right Pointers in Each Node I II
- mac使用nvm安装node进行多版本管理
- LintCode Remove Node in Binary Search Tree
- Node.js Cluster多进程负载测试
- [LeetCode]#19 Remove Nth Node From the End of list
- Node.js知识点详解(一)基础部分
- node.js框架express入门模板
- [LeetCode]Delete Node in a Linked List
- Grunt学习笔记之开发环境的搭建与创建一个基本的项目
- nodejs+express 初级安装测试
- 快速搭建 Node.js 开发环境
- nodejs爬虫简易实现和jquery的each方法
- nodejs显现events.js:72抛出错误
- LeetCode(38) Delete Node in a Linked List
- 执行start-dfs.sh后,datenode没有启动
- Node.js中的DNS模块