From 1350323379ee30ceba32f6ff8bb7d1c3fa1b8423 Mon Sep 17 00:00:00 2001 From: Sandarbh Singhal <123533242+Nothing-avil@users.noreply.github.com> Date: Sat, 30 Nov 2024 00:35:12 +0530 Subject: [PATCH] Create 2577_Minimum_Time_to_Visit_a_Cell_In_a_Grid.cpp --- ...Minimum_Time_to_Visit_a_Cell_In_a_Grid.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 2577_Minimum_Time_to_Visit_a_Cell_In_a_Grid.cpp diff --git a/2577_Minimum_Time_to_Visit_a_Cell_In_a_Grid.cpp b/2577_Minimum_Time_to_Visit_a_Cell_In_a_Grid.cpp new file mode 100644 index 0000000..b914f8c --- /dev/null +++ b/2577_Minimum_Time_to_Visit_a_Cell_In_a_Grid.cpp @@ -0,0 +1,50 @@ +// ███████╗ █████╗ ███╗ ██╗ ██████╗ █████╗ ██████╗ ██████╗ ██╗ ██╗ +// ██╔════╝ ██╔══██╗ ████╗ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║ ██║ +// ███████╗ ███████║ ██╔██╗ ██║ ██║ ██║ ███████║ ██████╔╝ ██████╔╝ ███████║ +// ╚════██║ ██╔══██║ ██║╚██╗██║ ██║ ██║ ██╔══██║ ██╔═██╗ ██╔══██╗ ██╔══██║ +// ███████║ ██║ ██║ ██║ ╚████║ ██████╔╝ ██║ ██║ ██║ ██╗ ██████╔╝ ██║ ██║ +// ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ +#pragma GCC optimize("Ofast", "inline", "ffast-math", "unroll-loops","no-stack-protector") +#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native", "f16c") +auto init = []() { + ios_base::sync_with_stdio(false); + cin.tie(nullptr); + cout.tie(nullptr); + return 'c'; +}(); +class Solution { +public: + int minimumTime(vector>& grid) { + if (grid[0][1] > 1 && grid[1][0] > 1) { + return -1; + } + int m = grid.size(), n = grid[0].size(); + int dist[m][n]; + memset(dist, 0x3f, sizeof dist); + dist[0][0] = 0; + using tii = tuple; + priority_queue, greater> pq; + pq.emplace(0, 0, 0); + int dirs[5] = {-1, 0, 1, 0, -1}; + while (1) { + auto [t, i, j] = pq.top(); + pq.pop(); + if (i == m - 1 && j == n - 1) { + return t; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + int nt = t + 1; + if (nt < grid[x][y]) { + nt = grid[x][y] + (grid[x][y] - nt) % 2; + } + if (nt < dist[x][y]) { + dist[x][y] = nt; + pq.emplace(nt, x, y); + } + } + } + } + } +};