- ๋ฐฉํฅ ๊ฐ์ค์น ๊ทธ๋ํ๊ฐ ์ฃผ์ด์ง๋ค.
start_node์์ end_node๋ก ๊ฐ๋ ๊ฒฝ๋ก ์ค ์ฑ๊ณต ํ๋ฅ ์ด ์ต๋๊ฐ ๋๋ ๊ฒฝ๋ก์ ํ๋ฅ ์ ๊ตฌํ๋ ๋ฌธ์ .
- ๊ฐ์ ์ ๊ฐ์ค์น๋ 0๊ณผ 1์ฌ์ด์ ํ๋ฅ ๊ฐ.
- ๊ฒฝ๋ก๊ฐ ์์ผ๋ฉด 0.0 ๋ฐํ
- ํ๋ฅ ์ ํฉ์ด ์๋๋ผ ๊ณฑ์ ๊ตฌํด์ผ ํจ!
๐ฏ ์ ๊ทผ ๋ฐฉ๋ฒ
๊ทธ๋ํ ํํ : ์ธ์ ๋ฆฌ์คํธ
Map<Integer, List<Edge>> graph๋ฅผ ์ฌ์ฉํ์ฌ ์ธ์ ๋ฆฌ์คํธ ํํ๋ก ํํ.
graph.get(u).add(new Edge(v, w)) , graph.get(v).add(newEdge(u, w))๋ก ์๋ฐฉํฅ ๊ทธ๋ํ๋ฅผ ๊ตฌ์ฑํ๋ค.
Edge ํด๋์ค๋ node ์ prob๋ฅผ ์ ์ฅํ๋ค.
๋ค์ต์คํธ๋ผ๋ฅผ ์ฌ์ฉํด ์ต๋ ํ๋ฅ ๊ฒฝ๋ก ๊ตฌํ๊ธฐ
๊ฑฐ๋ฆฌ ๋ฐฐ์ด ์ด๊ธฐํ
dist[node]๋ start_node์์ node๋ก ๊ฐ ์ ์๋ ๊ฐ์ฅ ๋์ ํ๋ฅ ์ ์ ์ฅ.
- ์ฒ์์๋
Arrays.fill(dist, 0)์ผ๋ก ์ด๊ธฐํ.
start_node์ ํ๋ฅ ์ 1๋ก ์ค์ ํ์ฌ ์์.
๋ค์ต์คํธ๋ผ ๋ฐ๋ณต ์ฒ๋ฆฌ
- ์ฐ์ ์์ ํ์์ ํ์ฌ ๋
ธ๋
curr๋ฅผ ๊บผ๋ด์, ํด๋น ๋
ธ๋์ ์ธ์ ๋
ธ๋๋ฅผ์ ์ํํ๋ค.
- ํ์ฌ ๋
ธ๋๊น์ง์ ํ๋ฅ
dist[curr.node]๊ณผ ํ์ฌ ๊ฐ์ ์ ํ๋ฅผ next.prob์ ๊ณฑํด
- ํด๋น ๋
ธ๋๊น์ง์ ์๋ก์ด ํ๋ฅ
nextDist๋ฅผ ๊ตฌํ๋ค.
- ๋ง์ฝ
dist[next.node] < nextDist์ด๋ผ๋ฉด,
- ๋ ๋์ ํ๋ฅ ๊ฒฝ๋ก๋ฅผ ์ฐพ์ ๊ฒ์ด๋ฏ๋ก, ๊ฐฑ์ ํ๊ณ
pq์ ์ฝ์
ํ์ฌ ๋ค์ ํ์์ ์์ฝํ๋ค.
- ์ด ๊ณผ์ ์ ํตํด ํ๋ฅ ์ ๊ณฑ์ด ๊ฐ์ฅ ๋์ ๊ฒฝ๋ก๋ถํฐ ํ์ํ๊ณ , ์ต์ข
์ ์ผ๋ก ๊ฐ์ฅ ๋์ ํ๋ฅ ์ ๊ตฌํ ์ ์๋ค!
์ต์ข
๋ฐํ
dist[end_node]๊ฐ start_node์์ end_node๊น์ง ๋๋ฌํ ์ ์๋ ๊ฐ์ฅ ๋์ ํ๋ฅ ์ด๋ฏ๋ก, ์ด๋ฅผ ๋ฐํํ๋ค.
- ๊ฒฝ๋ก๊ฐ ์์ผ๋ฉด
dist[end_node]๋ ์ฌ์ ํ 0์ด๋ฏ๋ก, ๋ฌธ์ ์กฐ๊ฑด์ ๋ง๊ฒ 0.0์ ๋ฐํํ๊ฒ ๋๋ค.
๐ ์ฝ๋ ๊ตฌํ
class Solution {
class Edge {
int node;
double prob;
Edge(int node, double prob) {
this.node = node;
this.prob = prob;
}
}
public double maxProbability(int n, int[][] edges, double[] succProb, int start_node, int end_node) {
Map<Integer, List<Edge>> graph = new HashMap<>();
for (int i = 0; i < n; i++) {
graph.put(i, new ArrayList<>());
}
for (int i = 0; i < edges.length; i++) {
int u = edges[i][0];
int v = edges[i][1];
double w = succProb[i];
graph.get(u).add(new Edge(v, w));
graph.get(v).add(new Edge(u, w));
}
double[] dist = new double[n];
Arrays.fill(dist, 0);
Queue<Edge> pq = new PriorityQueue<>((a, b) -> Double.compare(b.prob, a.prob));
pq.offer(new Edge(start_node, 1));
dist[start_node] = 1;
while (!pq.isEmpty()) {
Edge curr = pq.poll();
for (Edge next : graph.get(curr.node)) {
double nextDist = dist[curr.node] * next.prob;
if (dist[next.node] < nextDist) {
pq.add(new Edge(next.node, nextDist));
dist[next.node] = nextDist;
}
}
}
return dist[end_node];
}
}