Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 2311643

Browse files
committed
Add solution #802
1 parent 9eeacd7 commit 2311643

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

0802-find-eventual-safe-states.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,7 @@
283283
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
284284
791|[Custom Sort String](./0791-custom-sort-string.js)|Medium|
285285
796|[Rotate String](./0796-rotate-string.js)|Easy|
286+
802|[Find Eventual Safe States](./0802-find-eventual-safe-states.js)|Medium|
286287
804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy|
287288
819|[Most Common Word](./0819-most-common-word.js)|Easy|
288289
821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy|

0 commit comments

Comments
 (0)