面试题 04.01. Route Between Nodes LCCI
来源: LeetCode 面试题 04.01. Route Between Nodes LCCI
题目描述
面试题 04.01. Route Between Nodes LCCI
Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
Example1:
Input: n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
Output: true
Example2:
Input: n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4
Output true
Note:
0 <= n <= 100000
All node numbers are within the range [0, n].
There might be self cycles and duplicated edges.
思路分析
就是建邻接表然后入队时候判断加入就可以
代码
class Solution {
#define SIZE(A) ((int)A.size())
#define LENGTH(A) ((int)A.length())
#define MP(A,B) make_pair(A,B)
#define PB(X) push_back(X)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,a) for(int i=0;i<(a);++i)
#define ALL(A) A.begin(),A.end()
using VI = vector<int>;
using VII = vector<VI>;
using VD = vector<double>;
public:
bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
// bfs
// 创建图的结构
VI g[n];
for(auto e:graph) g[e[0]].PB(e[1]);
// 存储已经存储过的边
queue<int> q;
vector<bool>t(n,true); // 指示已经拜访过的数据
t[start] = false;
int cnt = n - 1;
for(auto v:g[start]){
if(v == target) return true;
if(t[v]){
q.push(v);
t[v] = false;
}
}
while(!q.empty() && cnt){
int n = SIZE(q);
REP(i,n){
int x = q.front();
q.pop(); cnt--;
for(auto v:g[x]){
if(v == target) return true;
if(t[v]) {
q.push(v);
t[v] = false;
}
}
}
}
return false;
}
};
算法分析
- 时间复杂度:O(e+v)
- 空间复杂度:O(e+v)