-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution1971.cs
60 lines (50 loc) · 1.53 KB
/
Solution1971.cs
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
59
60
namespace LeetCode.Solutions;
public class Solution1971
{
/// <summary>
/// 1971. Find if Path Exists in Graph
/// <a href="https://leetcode.com/problems/find-the-town-judge">See the problem</a>
/// </summary>
public bool ValidPath(int n, int[][] edges, int source, int destination)
{
var graph = new Dictionary<int, List<int>>();
// Build graph from edges list (undirected graph)
foreach (var edge in edges)
{
if (!graph.ContainsKey(edge[0]))
{
graph[edge[0]] = [];
}
if (!graph.ContainsKey(edge[1]))
{
graph[edge[1]] = [];
}
graph[edge[0]].Add(edge[1]);
graph[edge[1]].Add(edge[0]);
}
// BFS
var visited = new bool[n];
var queue = new Queue<int>();
queue.Enqueue(source);
while (queue.Count > 0)
{
var current = queue.Dequeue();
if (current == destination)
{
return true;
}
visited[current] = true;
if (graph.ContainsKey(current))
{
foreach (var neighbor in graph[current])
{
if (!visited[neighbor])
{
queue.Enqueue(neighbor);
}
}
}
}
return false;
}
}