From 7c60dee83b436e8e8a667bf9f191beced8de4fc3 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 10 Mar 2025 00:36:13 -0600 Subject: chore: move cpp and rust code to directory --- other/min_time_visit_cell_grid.cpp | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 other/min_time_visit_cell_grid.cpp (limited to 'other/min_time_visit_cell_grid.cpp') diff --git a/other/min_time_visit_cell_grid.cpp b/other/min_time_visit_cell_grid.cpp new file mode 100644 index 0000000..58a0099 --- /dev/null +++ b/other/min_time_visit_cell_grid.cpp @@ -0,0 +1,52 @@ +// 2577. Minimum Time to Visit a Cell In a Grid +#include "leetcode.h" + +/* + * you are given an 'm x n' matrix 'grid' consisting of non-negative integers + * where 'grid[row][col]' represents the minimum time required to be able to + * visit the cell '(row, col)', which means you can visit the cell '(row, col)' + * only when the time you visit it is greater than or equal to the value. you + * are standing in the top left cell of the matrix in the 0th second and you + * must move to any adjacent cell in the four directions: up, down, left, and + * right. each move you make takes 1 second. return the minimum time required in + * which you can visit the bottom right cell of the matrix. if you cannot visit + * the bottomright cell, then return -1. + */ + +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(); + vector> dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + vector> vis(m, vector(n, false)); + priority_queue, vector>, greater<>> pq; + pq.push({grid[0][0], 0, 0}); + while (!pq.empty()) { + int time = pq.top()[0], row = pq.top()[1], col = pq.top()[2]; + pq.pop(); + if (row == m - 1 && col == n - 1) + return time; + if (vis[row][col]) + continue; + vis[row][col] = true; + for (auto i : dir) { + int r = row + i[0], c = col + i[1]; + if (r < 0 || r >= m || c < 0 || c >= n || vis[r][c]) + continue; + int wait = !((grid[r][c] - time) % 2); + pq.push({max(grid[r][c] + wait, time + 1), r, c}); + } + } + return -1; + } +}; + +int main() { + Solution obj; + vvd g1 = {{0, 1, 3, 2}, {5, 1, 2, 5}, {4, 3, 8, 6}}, + g2 = {{0, 2, 4}, {3, 2, 1}, {1, 0, 4}}; + printf("%d\n", obj.minimumTime(g1)); // expect: 7 + printf("%d\n", obj.minimumTime(g2)); // expect: -1 +} -- cgit v1.2.3