面试题 04.01. 节点间通路 - 力扣(LeetCode)
bfs,dfs均可:
class Solution {
public:
vector<vector<int>> adj;
bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
if(start == target) return true;
adj = vector<vector<int>>(n, vector<int>());
for(const auto &v : graph) adj[v[0]].push_back(v[1]);
queue<int> q;
vector<int> visited(n, 0);//记录是否被访问过,防止环的出现
q.push(start);
visited[start] = 1;
while(!q.empty()){
int v =q.front();
q.pop();
for(const auto &w : adj[v]){
if(!visited[w]){
if(w == target) return true;
visited[w] = 1;
q.push(w);
}
}
}
return false;
}
};
class Solution {
public:
vector<vector<int>> adj;
vector<int> visited;//记录是否被访问过,防止环的出现
bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
adj = vector<vector<int>>(n, vector<int>());
for(const auto &v : graph) adj[v[0]].push_back(v[1]);
visited = vector<int>(n, 0);
return dfs(start, target);
}
bool dfs(int s, int t){
if(s == t) return true;
visited[s] = 1;
for(const auto &w : adj[s]){
if(!visited[w] && dfs(w, t)) return true;
}
return false;
}
};