https://leetcode.com/problems/path-with-maximum-probability/description/
주어진 그래프에서 시작 노드부터 끝 노드에 도착할 수 있는 경로 중 최대 확률을 구하는 문제입니다.
입력
n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
출력
0.25
입력
n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
출력
0.3
입력
n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
출력
0
이 문제는 그래프 탐색 문제로, 주어진 간선들의 확률을 바탕으로 시작 노드부터 끝 노드에 도착할 수 있는 경로 중 최대 확률을 구하는 문제입니다. 이 문제를 풀기 위해서는 다익스트라 알고리즘을 변형한 방법을 사용할 수 있습니다. 다익스트라 알고리즘은 최단 경로를 찾는 알고리즘이지만, 이를 최대 확률 경로로 변형하여 사용할 수 있습니다.
확률을 구할 때 곱셈을 사용하므로, 최대 확률을 구하는 데 있어서 우선순위 큐를 활용하여 가장 큰 확률부터 탐색해야 합니다.
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
class Node {
int v;
double weight;
public Node(int v, double weight) {
this.v = v;
this.weight = weight;
}
}
class Solution {
public static List<List<Node>> graph;
public double maxProbability(int n, int[][] edges, double[] succProb, int start_node, int end_node) {
graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < edges.length; i++) {
int v1 = edges[i][0];
int v2 = edges[i][1];
double weight = succProb[i];
graph.get(v1).add(new Node(v2, weight));
graph.get(v2).add(new Node(v1, weight));
}
return dijkstra(n, start_node, end_node);
}
private double dijkstra(int n, int start_node, int end_node) {
double[] dist = new double[n];
dist[start_node] = 1;
PriorityQueue<Node> pq = new PriorityQueue<>((o1, o2) -> Double.compare(o2.weight, o1.weight));
pq.add(new Node(start_node, 1));
while (!pq.isEmpty()) {
Node cur = pq.poll();
if (cur.weight < dist[cur.v]) continue;
for (Node next : graph.get(cur.v)) {
double nextWeight = cur.weight * next.weight;
if (dist[next.v] < nextWeight) {
dist[next.v] = nextWeight;
pq.add(new Node(next.v, nextWeight));
}
}
}
return dist[end_node];
}
}