| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.FindEventualSafeStates; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class FindEventualSafeStatesDepthFirstSearch : IFindEventualSafeStates |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n + E), where n is a number of nodes, E is a number of edges |
| | | 19 | | /// Space complexity - O(n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="graph"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public IList<int> EventualSafeNodes(int[][] graph) |
| | 2 | 24 | | { |
| | 2 | 25 | | var n = graph.Length; |
| | | 26 | | |
| | 2 | 27 | | Span<int> states = stackalloc int[n]; |
| | | 28 | | |
| | 2 | 29 | | var result = new List<int>(); |
| | | 30 | | |
| | 28 | 31 | | for (var node = 0; node < n; node++) |
| | 12 | 32 | | { |
| | 12 | 33 | | if (!IsSafeNode(node, graph, states)) |
| | 7 | 34 | | { |
| | 7 | 35 | | continue; |
| | | 36 | | } |
| | | 37 | | |
| | 5 | 38 | | result.Add(node); |
| | 5 | 39 | | } |
| | | 40 | | |
| | 2 | 41 | | return result; |
| | 2 | 42 | | } |
| | | 43 | | |
| | | 44 | | private static bool IsSafeNode(int node, int[][] graph, Span<int> states) |
| | 22 | 45 | | { |
| | 22 | 46 | | switch (states[node]) |
| | | 47 | | { |
| | 3 | 48 | | case 1: return true; |
| | 7 | 49 | | case 2: return false; |
| | | 50 | | } |
| | | 51 | | |
| | 12 | 52 | | var adjacentNodes = graph[node]; |
| | 12 | 53 | | var adjacentNodesLength = adjacentNodes.Length; |
| | | 54 | | |
| | 12 | 55 | | states[node] = 2; |
| | | 56 | | |
| | 30 | 57 | | for (var i = 0; i < adjacentNodesLength; i++) |
| | 10 | 58 | | { |
| | 10 | 59 | | var adjacentNode = graph[node][i]; |
| | | 60 | | |
| | 10 | 61 | | if (IsSafeNode(adjacentNode, graph, states)) |
| | 3 | 62 | | { |
| | 3 | 63 | | continue; |
| | | 64 | | } |
| | | 65 | | |
| | 7 | 66 | | return false; |
| | | 67 | | } |
| | | 68 | | |
| | 5 | 69 | | states[node] = 1; |
| | | 70 | | |
| | 5 | 71 | | return true; |
| | 22 | 72 | | } |
| | | 73 | | } |