Skip to content

Added FindPathsExists #539

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions Graph/FindPathExistsInGraph
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
Problem statement is -There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.

You want to determine if there is a valid path that exists from vertex source to vertex destination.

Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.



## solotion
class Solution {
public:
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
vector<vector<int>>adj(n);
queue<int>q;
vector<bool>visited(n+1,false);

for(auto x : edges){
auto u=x.front();
auto v=x.back();
adj[u].push_back(v);
adj[v].push_back(u);
}
q.push(source);
visited[source]=true;

while(!q.empty()){
auto temp=q.front();
q.pop();

for(auto vertex : adj[temp]){
if(!visited[vertex]){
visited[vertex]=true;
q.push(vertex);
}


}
}
return visited[destination];
}
};