File tree 2 files changed +37
-0
lines changed
2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 802. Find Eventual Safe States
3
+ * https://leetcode.com/problems/find-eventual-safe-states/
4
+ * Difficulty: Medium
5
+ *
6
+ * There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is
7
+ * represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of
8
+ * nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].
9
+ *
10
+ * A node is a terminal node if there are no outgoing edges. A node is a safe node if every
11
+ * possible path starting from that node leads to a terminal node (or another safe node).
12
+ *
13
+ * Return an array containing all the safe nodes of the graph. The answer should be sorted
14
+ * in ascending order.
15
+ */
16
+
17
+ /**
18
+ * @param {number[][] } graph
19
+ * @return {number[] }
20
+ */
21
+ var eventualSafeNodes = function ( graph ) {
22
+ const nodes = graph . map ( ( ) => [ ] ) ;
23
+ const totals = graph . map ( n => n . length ) ;
24
+ const queue = totals . map ( ( v , i ) => v ? - 1 : i ) . filter ( v => v >= 0 ) ;
25
+ const result = [ ] ;
26
+
27
+ graph . forEach ( ( n , i ) => n . forEach ( v => nodes [ v ] . push ( i ) ) ) ;
28
+
29
+ while ( queue . length ) {
30
+ const node = queue . shift ( ) ;
31
+ result . push ( node ) ;
32
+ nodes [ node ] . forEach ( v => ! -- totals [ v ] && queue . push ( v ) ) ;
33
+ }
34
+
35
+ return result . sort ( ( a , b ) => a - b ) ;
36
+ } ;
Original file line number Diff line number Diff line change 283
283
784|[ Letter Case Permutation] ( ./0784-letter-case-permutation.js ) |Medium|
284
284
791|[ Custom Sort String] ( ./0791-custom-sort-string.js ) |Medium|
285
285
796|[ Rotate String] ( ./0796-rotate-string.js ) |Easy|
286
+ 802|[ Find Eventual Safe States] ( ./0802-find-eventual-safe-states.js ) |Medium|
286
287
804|[ Unique Morse Code Words] ( ./0804-unique-morse-code-words.js ) |Easy|
287
288
819|[ Most Common Word] ( ./0819-most-common-word.js ) |Easy|
288
289
821|[ Shortest Distance to a Character] ( ./0821-shortest-distance-to-a-character.js ) |Easy|
You can’t perform that action at this time.
0 commit comments