Skip to content

Latest commit

 

History

History
207 lines (181 loc) · 6.69 KB

File metadata and controls

207 lines (181 loc) · 6.69 KB

中文文档

Description

Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.

The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi.

Return the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted.

 

Example 1:

Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
Output: 0.16666666666666666 
Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. 

Example 2:

Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7
Output: 0.3333333333333333
Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. 

 

Constraints:

  • 1 <= n <= 100
  • edges.length == n - 1
  • edges[i].length == 2
  • 1 <= ai, bi <= n
  • 1 <= t <= 50
  • 1 <= target <= n

Solutions

BFS.

Python3

class Solution:
    def frogPosition(
        self, n: int, edges: List[List[int]], t: int, target: int
    ) -> float:
        g = defaultdict(list)
        for u, v in edges:
            g[u].append(v)
            g[v].append(u)
        q = deque([(1, 1.0)])
        vis = [False] * (n + 1)
        vis[1] = True
        while q and t >= 0:
            for _ in range(len(q)):
                u, p = q.popleft()
                nxt = [v for v in g[u] if not vis[v]]
                if u == target and (not nxt or t == 0):
                    return p
                for v in nxt:
                    vis[v] = True
                    q.append((v, p / len(nxt)))
            t -= 1
        return 0

Java

class Solution {
    public double frogPosition(int n, int[][] edges, int t, int target) {
        List<Integer>[] g = new List[n + 1];
        Arrays.setAll(g, k -> new ArrayList<>());
        for (int[] e : edges) {
            int u = e[0], v = e[1];
            g[u].add(v);
            g[v].add(u);
        }
        Deque<Pair<Integer, Double>> q = new ArrayDeque<>();
        q.offer(new Pair<>(1, 1.0));
        boolean[] vis = new boolean[n + 1];
        vis[1] = true;
        while (!q.isEmpty() && t >= 0) {
            for (int k = q.size(); k > 0; --k) {
                Pair<Integer, Double> x = q.poll();
                int u = x.getKey();
                double p = x.getValue();
                List<Integer> nxt = new ArrayList<>();
                for (int v : g[u]) {
                    if (!vis[v]) {
                        nxt.add(v);
                        vis[v] = true;
                    }
                }
                if (u == target && (nxt.isEmpty() || t == 0)) {
                    return p;
                }
                for (int v : nxt) {
                    q.offer(new Pair<>(v, p / nxt.size()));
                }
            }
            --t;
        }
        return 0;
    }
}

C++

class Solution {
public:
    double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
        vector<vector<int>> g(n + 1);
        for (auto& e : edges) {
            int u = e[0], v = e[1];
            g[u].push_back(v);
            g[v].push_back(u);
        }
        typedef pair<int, double> pid;
        queue<pid> q;
        q.push({1, 1.0});
        vector<bool> vis(n + 1);
        vis[1] = true;
        while (!q.empty() && t >= 0) {
            for (int k = q.size(); k; --k) {
                auto x = q.front();
                q.pop();
                int u = x.first;
                double p = x.second;
                vector<int> nxt;
                for (int v : g[u]) {
                    if (!vis[v]) {
                        vis[v] = true;
                        nxt.push_back(v);
                    }
                }
                if (u == target && (t == 0 || nxt.empty())) return p;
                for (int v : nxt) q.push({v, p / nxt.size()});
            }
            --t;
        }
        return 0;
    }
};

Go

type pid struct {
	x int
	p float64
}

func frogPosition(n int, edges [][]int, t int, target int) float64 {
	g := make([][]int, n+1)
	for _, e := range edges {
		u, v := e[0], e[1]
		g[u] = append(g[u], v)
		g[v] = append(g[v], u)
	}
	q := []pid{pid{1, 1.0}}
	vis := make([]bool, n+1)
	vis[1] = true
	for len(q) > 0 && t >= 0 {
		for k := len(q); k > 0; k-- {
			x := q[0]
			q = q[1:]
			u, p := x.x, x.p
			var nxt []int
			for _, v := range g[u] {
				if !vis[v] {
					vis[v] = true
					nxt = append(nxt, v)
				}
			}
			if u == target && (len(nxt) == 0 || t == 0) {
				return p
			}
			for _, v := range nxt {
				q = append(q, pid{v, p / float64(len(nxt))})
			}
		}
		t--
	}
	return 0
}

...