Q4.2 Given a directed graph, design an algorithm to find out whether there is a route.
来源:互联网 发布:2017年淘宝天猫电商节 编辑:程序博客网 时间:2024/06/13 22:10
Q: Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
A: 采用bfs, 同时利用哈希表保存当前节点是否已经被访问了。
如果节点i 和节点j 相连,并且j没有被访问过,那么节点j入栈,说明节点j可能是所求路径上的点。
就这样遍历,直到栈为空或者到达终点。
#include <iostream>#include <queue>#include <cmath>using namespace std;const int maxn = 10;bool g[maxn][maxn], visited[maxn];int n;queue<int> q;void init(){ memset(g, false, sizeof(g)); memset(visited, false, sizeof(visited));}bool route(int src, int dst){ q.push(src); visited[src] = true; while(!q.empty()){ int t = q.front(); q.pop(); if(t == dst) return true; for(int i=0; i<n; ++i) if(g[t][i] && !visited[i]){ q.push(i); visited[i] = true; } } return false;}int main(){ init(); int m, u, v; cin>>n>>m; for(int i=0; i<m; ++i){ cin>>u>>v; g[u][v] = true; } cout<<route(0, 6)<<endl; return 0;}
0 0
- Q4.2 Given a directed graph, design an algorithm to find out whether there is a route.
- leetCode Given an integer (signed 32 bits), write a function to check whether it is a power of 4
- Geeks - Check whether a given graph is Bipartite or not 二分图检查
- Find whether a given number is a power of 4 or not
- CareerCup Find whether a given number is a perfect square or not.(Addition and Subtraction only)
- is-there-a-way-to-test-whether-a-c-class-has-a-default-constructor-other-than
- Q4.9 Find all paths which sum to a given value
- Given a number m, how to decide whether this m is in the matrix
- CareerCup Given an array having positive integers, find a subarray which adds to a given number
- P31 (**) Determine whether a given integer number is prime.
- Connectivity in a directed graph
- 4 4 Given a binary search tree, design an algorithm which creates a linked list of all the nodes at
- Write one line C function to find whether a no is power of two
- Given an array A[i..j] find out maximum j-i such that A[i]<a[j]
- Geeks - Union-Find Algorithm - Detect Cycle in a an Undirected Graph算法
- Is there a way to add a badge to an application icon in Android?
- Check whether a java instance is belonging to a class
- 3、Determine whether an integer is a palindrome
- 《机器学习技法》第七讲:Blending and Bagging
- What day is it(1246)
- CentOS使用光盘作为本地源
- 解决HWM带来性能问题
- Chronometer组件实现计时器小程序
- Q4.2 Given a directed graph, design an algorithm to find out whether there is a route.
- 几种常用的Java设计模式
- 机器的智慧
- [最短路径] HDU 2066 - 一个人的旅行
- unity进度条,物品随机掉落
- 第四章 模板
- win7 下安装mysql 整理
- 黑马程序员------Java概要
- c++中的#include "stdafx.h"