# 1971. 寻找图中是否存在路径

# 题解

class Solution {
public:
bool dfs(int source, int destination, vector<vector<int>> &adj, vector<bool> &visited) {
if (source == destination) {
return true;
}
visited[source] = true;
for (int next : adj[source]) {
if (!visited[next] && dfs(next, destination, adj, visited)) {
return true;
}
}
return false;
}

bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
vector<vector<int>> adj(n);
for (auto &edge : edges) {
int x = edge[0], y = edge[1];
adj[x].emplace_back(y);
adj[y].emplace_back(x);
}
vector<bool> visited(n, false);
return dfs(source, destination, adj, visited);
}
};

复杂度分析

  • 时间复杂度:$O (m+n)$
  • 空间复杂度:$O (m+n)$