diff --git a/Leetcode/1631/ysuh/README.md b/Leetcode/1631/ysuh/README.md new file mode 100644 index 0000000..e0baa3c --- /dev/null +++ b/Leetcode/1631/ysuh/README.md @@ -0,0 +1,13 @@ +## Link +[Path With Minimum Effort](https://leetcode.com/problems/path-with-minimum-effort/description/) + +## Topic +- Dijkstra +- Priority Queue + +## Approach +- We define possible direction in each cell (left, right, up, down) +- Using relaxation and maximum effort, run dijkstra + +## Note +- Terminating when arrived at ROW-1, COL-1 idx remarkably shrinks the computation time. diff --git a/Leetcode/1631/ysuh/solution.cpp b/Leetcode/1631/ysuh/solution.cpp new file mode 100644 index 0000000..e0f3509 --- /dev/null +++ b/Leetcode/1631/ysuh/solution.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int move_hor[4] = {-1, 0, 1, 0}; + int move_ver[4] = {0, -1, 0, 1}; + int ROW; + int COL; + int dijkstra(vector>& heights, vector>& min_effort) { + min_effort[0][0] = 0; + priority_queue>> pq; + pq.push({0, {0, 0}}); + while (!pq.empty()) { + auto tmp = pq.top(); + int eff = -tmp.first; + int idx_r = tmp.second.first; + int idx_c = tmp.second.second; + if (idx_r == ROW-1 && idx_c == COL-1) return min_effort[ROW-1][COL-1]; + pq.pop(); + for (int i=0; i<4; i++) { + int new_row = idx_r + move_hor[i]; + int new_col = idx_c + move_ver[i]; + if (new_row < ROW && new_row > -1 && new_col < COL && new_col > -1) { + int cost = max(eff, abs(heights[new_row][new_col] - heights[idx_r][idx_c])); + if (cost < min_effort[new_row][new_col]) { + min_effort[new_row][new_col] = cost; + pq.push({-cost, {new_row, new_col}}); + } + } + } + } + return min_effort[ROW-1][COL-1]; + + } + int minimumEffortPath(vector>& heights) { + ROW = heights.size(); + COL = heights[0].size(); + vector> min_effort(ROW, vector(COL, 1e9)); + return dijkstra(heights, min_effort); + } +};