|
| 1 | +/** |
| 2 | + * 1377. Frog Position After T Seconds |
| 3 | + * https://leetcode.com/problems/frog-position-after-t-seconds/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts |
| 7 | + * jumping from vertex 1. In one second, the frog jumps from its current vertex to another |
| 8 | + * unvisited vertex if they are directly connected. The frog can not jump back to a visited |
| 9 | + * vertex. In case the frog can jump to several vertices, it jumps randomly to one of them |
| 10 | + * with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, |
| 11 | + * it jumps forever on the same vertex. |
| 12 | + * |
| 13 | + * The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] |
| 14 | + * means that exists an edge connecting the vertices ai and bi. |
| 15 | + * |
| 16 | + * Return the probability that after t seconds the frog is on the vertex target. Answers |
| 17 | + * within 10-5 of the actual answer will be accepted. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number} n |
| 22 | + * @param {number[][]} edges |
| 23 | + * @param {number} t |
| 24 | + * @param {number} target |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var frogPosition = function(n, edges, t, target) { |
| 28 | + const adjacencyList = Array.from({ length: n + 1 }, () => []); |
| 29 | + for (const [a, b] of edges) { |
| 30 | + adjacencyList[a].push(b); |
| 31 | + adjacencyList[b].push(a); |
| 32 | + } |
| 33 | + |
| 34 | + return explore(1, 0, 1, new Set()); |
| 35 | + |
| 36 | + function explore(vertex, time, probability, visited) { |
| 37 | + if (time > t) return 0; |
| 38 | + if (vertex === target && time === t) return probability; |
| 39 | + if (vertex === target && adjacencyList[vertex].every(v => visited.has(v))) return probability; |
| 40 | + |
| 41 | + const unvisitedNeighbors = adjacencyList[vertex].filter(v => !visited.has(v)); |
| 42 | + if (unvisitedNeighbors.length === 0) return 0; |
| 43 | + |
| 44 | + const nextProbability = probability / unvisitedNeighbors.length; |
| 45 | + visited.add(vertex); |
| 46 | + |
| 47 | + for (const neighbor of unvisitedNeighbors) { |
| 48 | + const result = explore(neighbor, time + 1, nextProbability, visited); |
| 49 | + if (result > 0) return result; |
| 50 | + } |
| 51 | + |
| 52 | + return 0; |
| 53 | + } |
| 54 | +}; |
0 commit comments