From 1ade1562255c608bb6597e6e0d4e252be13b4882 Mon Sep 17 00:00:00 2001 From: InSange Date: Tue, 3 Dec 2024 05:15:13 +0900 Subject: [PATCH] 2024-12-03 Minimum Time to Visit a Cell In a Grid --- ...Minimum Time to Visit a Cell In a Grid.cpp | 57 +++++++++++++++++++ InSange/README.md | 4 +- 2 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 InSange/BFS/2577. Minimum Time to Visit a Cell In a Grid.cpp diff --git a/InSange/BFS/2577. Minimum Time to Visit a Cell In a Grid.cpp b/InSange/BFS/2577. Minimum Time to Visit a Cell In a Grid.cpp new file mode 100644 index 0000000..392d242 --- /dev/null +++ b/InSange/BFS/2577. Minimum Time to Visit a Cell In a Grid.cpp @@ -0,0 +1,57 @@ +#include +#include + +using namespace std; + +class Solution { +public: + int minimumTime(vector>& grid) { + if (grid[0][1] > 1 && grid[1][0] > 1) // ִ ó + { + return -1; + } + + int row = grid.size(); + int col = grid[0].size(); + + vector> val; + val.assign(row, vector(col, INT_MAX)); + + priority_queue, vector>, greater<>> pq; + int dy[4] = { 0, 0, -1, 1 }; + int dx[4] = { 1, -1, 0, 0 }; + + pq.push({ 0, 0, 0 }); + val[0][0] = 0; + + while (!pq.empty()) + { + int curY = pq.top()[1]; + int curX = pq.top()[2]; + int curTime = pq.top()[0]; + pq.pop(); + + if (curY == row - 1 && curX == col - 1) + { + return curTime; + } + + for (int i = 0; i < 4; i++) + { + int nextY = curY + dy[i]; + int nextX = curX + dx[i]; + + if (nextY < 0 || nextY >= row || nextX < 0 || nextX >= col) continue; // Out of Bounds + int nextTime = max(curTime + 1, grid[nextY][nextX] + ((grid[nextY][nextX] - curTime) % 2 == 0 ? 1 : 0)); + + if (val[nextY][nextX] > nextTime) + { + pq.push({ nextTime, nextY, nextX }); + val[nextY][nextX] = nextTime; + } + } + } + + return -1; + } +}; \ No newline at end of file diff --git a/InSange/README.md b/InSange/README.md index b73134a..d4189b2 100644 --- a/InSange/README.md +++ b/InSange/README.md @@ -33,7 +33,5 @@ | 29차시 | 2024.08.25 | 문자열 | [Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/) | [#29](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/98)] | 30차시 | 2024.09.06 | 문자열 | [Delete Nodes From Linked List Present in Array](https://leetcode.com/problems/delete-nodes-from-linked-list-present-in-array/) | [#30](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/100)] | 31차시 | 2024.12.01 | DFS | [Valid Arrangement of Pairs](https://leetcode.com/problems/valid-arrangement-of-pairs/) | [#31](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/101)] +| 32차시 | 2024.12.03 | BFS | [Minimum Time to Visit a Cell In a Grid](https://leetcode.com/problems/minimum-time-to-visit-a-cell-in-a-grid/) | [#32](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/102)] --- - -https://leetcode.com/problems/robot-collisions/ -Find the Closest Palindrome \ No newline at end of file