|
| 1 | +/** |
| 2 | + * @param {number} n |
| 3 | + * @param {number[][]} edges |
| 4 | + * @param {number} t |
| 5 | + * @param {number} target |
| 6 | + * @return {number} |
| 7 | + */ |
| 8 | +const frogPosition = function (n, edges, t, target) { |
| 9 | + const graph = { 1: new Set() } |
| 10 | + for (let [from, to] of edges) { |
| 11 | + if (graph[from]) graph[from].add(to) |
| 12 | + else graph[from] = new Set([to]) |
| 13 | + if (graph[to]) graph[to].add(from) |
| 14 | + else graph[to] = new Set([from]) |
| 15 | + } |
| 16 | + |
| 17 | + // dfs through the graph storing the vetices you've visited, number of jumps, and current vertice |
| 18 | + const dfs = (from, numJumps, visited) => { |
| 19 | + // if the count equals t then return 1 if the vertice is the target |
| 20 | + if (numJumps === t) return from === target ? 1 : 0 |
| 21 | + |
| 22 | + // average out all the next results |
| 23 | + let numEdgesCanJump = 0 |
| 24 | + let total = 0 |
| 25 | + for (let to of graph[from]) { |
| 26 | + if (visited.has(to)) continue |
| 27 | + visited.add(to) |
| 28 | + total += dfs(to, numJumps + 1, visited) |
| 29 | + visited.delete(to) |
| 30 | + numEdgesCanJump++ |
| 31 | + } |
| 32 | + |
| 33 | + // if we can jump, average all the next results |
| 34 | + // otherwise we can't jump anywhere and return 1 if we are at the target |
| 35 | + // if we are not at the target return 0 |
| 36 | + if (numEdgesCanJump > 0) { |
| 37 | + return total / numEdgesCanJump |
| 38 | + } |
| 39 | + return from === target ? 1 : 0 |
| 40 | + } |
| 41 | + return dfs(1, 0, new Set([1])) |
| 42 | +} |
0 commit comments