From bc4b8f2d9ccea683ba386344961ae1228e94815c Mon Sep 17 00:00:00 2001 From: Youngsang Suh <60172447+youngsangsuh@users.noreply.github.com> Date: Fri, 26 May 2023 17:33:01 -0700 Subject: [PATCH 1/2] Create solution.cpp --- Leetcode/1631/ysuh/solution.cpp | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Leetcode/1631/ysuh/solution.cpp 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); + } +}; From 19a5be9f4be5218db329f8e11dc970408339256f Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sat, 27 May 2023 00:35:48 +0000 Subject: [PATCH 2/2] Add README.md file --- Leetcode/1631/ysuh/README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Leetcode/1631/ysuh/README.md 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.