-
Notifications
You must be signed in to change notification settings - Fork 1
/
Find if path exist in graph.cc
58 lines (49 loc) · 1.49 KB
/
Find if path exist in graph.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution {
public:
bool findIfPathExistsInGraphDfs(const std::vector<std::vector<int>>& adjacencyList,
std::vector<bool>& isVisited,
const int& source, const int& destination)
{
if (isVisited[source] == true)
{
return false;
}
isVisited[source] = true;
bool returnVal = false;
for (int i = 0; i < adjacencyList[source].size(); i++)
{;
if (adjacencyList[source][i] == destination)
{
returnVal = true;
break;
}
else if (findIfPathExistsInGraphDfs(adjacencyList, isVisited, adjacencyList[source][i], destination))
{
returnVal = true;
break;
}
}
return returnVal;
}
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
if(edges.size() == 0)
{
return true;
}
std::vector<std::vector<int>> adjacencyList(n);
std::vector<bool> isVisited(n);
for (int i = 0; i < edges.size(); i++)
{
adjacencyList[edges[i][0]].emplace_back(edges[i][1]);
adjacencyList[edges[i][1]].emplace_back(edges[i][0]);
}
for (int i = 0; i < adjacencyList.size(); i++)
{
if (findIfPathExistsInGraphDfs(adjacencyList, isVisited, source, destination))
{
return true;
}
}
return false;
}
};