| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.FindIfPathExistsInGraph; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FindIfPathExistsInGraphDepthFirstSearch : IFindIfPathExistsInGraph |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(v + e), where v is the number of vertices and e is the number of edges |
| | 19 | | /// Space complexity - O(v + e), where v is the number of vertices and e is the number of edges |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <param name="edges"></param> |
| | 23 | | /// <param name="source"></param> |
| | 24 | | /// <param name="destination"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public bool ValidPath(int n, int[][] edges, int source, int destination) |
| 2 | 27 | | { |
| 2 | 28 | | if (source == destination) |
| 0 | 29 | | { |
| 0 | 30 | | return true; |
| | 31 | | } |
| | 32 | |
|
| 2 | 33 | | var graph = new Dictionary<int, List<int>>(); |
| | 34 | |
|
| 22 | 35 | | for (var i = 0; i < n; i++) |
| 9 | 36 | | { |
| 9 | 37 | | graph[i] = []; |
| 9 | 38 | | } |
| | 39 | |
|
| 22 | 40 | | foreach (var edge in edges) |
| 8 | 41 | | { |
| 8 | 42 | | graph[edge[0]].Add(edge[1]); |
| 8 | 43 | | graph[edge[1]].Add(edge[0]); |
| 8 | 44 | | } |
| | 45 | |
|
| 2 | 46 | | return ValidPath(new HashSet<int>(), graph, source, destination); |
| 2 | 47 | | } |
| | 48 | |
|
| | 49 | | private static bool ValidPath(ISet<int> visited, IReadOnlyDictionary<int, List<int>> graph, int current, int target) |
| 6 | 50 | | { |
| 6 | 51 | | if (current == target) |
| 1 | 52 | | { |
| 1 | 53 | | return true; |
| | 54 | | } |
| | 55 | |
|
| 5 | 56 | | visited.Add(current); |
| | 57 | |
|
| 5 | 58 | | return graph[current] |
| 12 | 59 | | .Any(neighbor => !visited.Contains(neighbor) && ValidPath(visited, graph, neighbor, target)); |
| 6 | 60 | | } |
| | 61 | | } |