(Leetcode) [Graph, Dijkstra] Path with maximum probability

Question

https://leetcode.com/problems/path-with-maximum-probability/


Topic: Graph using Dijkstra

Dijkstra Algorithm

  • shortest path ํƒ์ƒ‰
  • negative weight ํฌํ•จ ๋ถˆ๊ฐ€๋Šฅ
  • dynamic programming์„ ํ™œ์šฉ
    • ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•  ๋•Œ ๊ทธ ์ด์ „๊นŒ์ง€ ๊ตฌํ–ˆ๋˜ ์ตœ๋‹จ๊ฑฐ๋ฆฌ ์ •๋ณด๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•œ๋‹ค

๊ณผ์ •:

  1. ์‹œ์ž‘ ๋…ธ๋“œ ์„ค์ •
  2. ์‹œ์ž‘ ๋…ธ๋“œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ฐ ๋…ธ๋“œ์˜ minimum weight ์ €์žฅ
  3. unvisited node ์ค‘์—์„œ minimum weight์˜ ๋…ธ๋“œ๋ฅผ ์„ ํƒ
  4. ํ•ด๋‹น ๋…ธ๋“œ๋ฅผ ๊ฑฐ์ณ์„œ ํŠน์ • ๋…ธ๋“œ๋กœ ๊ฐ€๋Š” ๊ฒฝ์šฐ๋ฅผ ๊ณ ๋ คํ•˜์—ฌ min cost ๊ฐฑ์‹ 
  5. 3 & 4 ๋ฐ˜๋ณต


์œ ํŠœ๋ธŒ์—์„œ ๋‹ค์ต์ŠคํŠธ๋ผ๋ฅผ ์ด์šฉํ•˜๊ธฐ ์œ„ํ•œ ๊ทธ๋ž˜ํ”„ ํด๋ž˜์Šค์™€ ๋‹ค์ต์ŠคํŠธ๋ผ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ ๊ฑธ ์ฐธ๊ณ ํ•ด์„œ ํ’€์—ˆ๋‹ค.
pair์™€ priority queue๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.
์ด๋ฒˆ ๋ฌธ์ œ๋Š” ์ตœ๋Œ€ ํ™•๋ฅ ์„ ์ฐพ๋Š” ๋ฌธ์ œ์—ฌ์„œ ๋‹ค์ต์ŠคํŠธ๋ผ๋ฅผ ์ด์šฉํ•˜๋ ค๋ฉด ๋ชจ๋“  ๊ฐ„์„ (distance)์— -1์„ ๊ณฑํ•ด์•ผํ–ˆ๋‹ค.
๊ทธ๋ž˜์•ผ ์ ˆ๋Œ€๊ฐ’์ด ์ œ์ผ ํฐ ์ˆ˜ (์ œ์ผ ์ž‘์€ ์Œ์ˆ˜)๊ฐ€ ํ์˜ ์ œ์ผ ์œ„์— ์œ„์น˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.
e.g. top (-0.9, -0.5, -0.1) bottom

๊ทธ๋ฆฌ๊ณ  ํ•จ์ˆ˜์—์„œ ํ™•๋ฅ ์„ ๋ฐ˜ํ™˜ํ•  ๋•Œ -1์„ ๊ณฑํ•œ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋œ๋‹ค.


Source code: https://github.com/sungjin122517/leetcode/blob/main/graph/path-with-max-probability.cpp
Reference: https://www.youtube.com/watch?v=OHJpOGa_L34

Categories:

Updated:

Leave a comment