Skip to content

Commit d7d2fb6

Browse files
authored
Update minimum-cost-to-make-at-least-one-valid-path-in-a-grid.cpp
1 parent 7e2effd commit d7d2fb6

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

C++/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.cpp

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class Solution {
1818
{3, 1, 0}, {4, -1, 0}};
1919
int f = 0, dh = 1;
2020
vector<pair<int, int>> closer = {b}, detour;
21-
unordered_set<int> lookup;
21+
vector<vector<bool>> lookup(size(grid), vector<bool>(size(grid[0])));
2222
while (!closer.empty() || !detour.empty()) {
2323
if (closer.empty()) {
2424
f += dh;
@@ -28,15 +28,15 @@ class Solution {
2828
if (b == t) {
2929
return f;
3030
}
31-
if (lookup.count(b.first * grid[0].size() + b.second)) {
31+
if (lookup[b.first][b.second]) {
3232
continue;
3333
}
34-
lookup.emplace(b.first * grid[0].size() + b.second);
34+
lookup[b.first][b.second] = true;
3535
for (const auto& [nd, dr, dc] : directions) {
3636
const pair<int, int>& nb = {b.first + dr, b.second + dc};
3737
if (!(0 <= nb.first && nb.first < grid.size() &&
3838
0 <= nb.second && nb.second < grid[0].size() &&
39-
!lookup.count(nb.first * grid[0].size() + nb.second))) {
39+
!lookup[nb.first][nb.second])) {
4040
continue;
4141
}
4242
if (nd == grid[b.first][b.second]) {
@@ -60,22 +60,22 @@ class Solution2 {
6060
{3, 1, 0}, {4, -1, 0}};
6161
const pair<int, int> b = {0, 0}, t = {grid.size() - 1, grid[0].size() - 1};
6262
deque<pair<pair<int, int>, int>> dq = {{b, 0}};
63-
unordered_set<int> lookup;
63+
vector<vector<bool>> lookup(size(grid), vector<bool>(size(grid[0])));
6464
while (!dq.empty()) {
6565
const auto [b, d] = dq.front(); dq.pop_front();
6666
if (b == t) {
6767
return d;
6868
}
69-
if (lookup.count(b.first * grid[0].size() + b.second)) {
69+
if (lookup[b.first][b.second]) {
7070
continue;
7171
}
72-
lookup.emplace(b.first * grid[0].size() + b.second);
72+
lookup[b.first][b.second] = true;
7373
for (const auto& [nd, dr, dc] : directions) {
7474
const auto& nb = make_pair(b.first + dr, b.second + dc);
7575
const auto& cost = nd != grid[b.first][b.second] ? 1 : 0;
7676
if (!(0 <= nb.first && nb.first < grid.size() &&
7777
0 <= nb.second && nb.second < grid[0].size() &&
78-
!lookup.count(nb.first * grid[0].size() + nb.second))) {
78+
!lookup[nb.first][nb.second])) {
7979
continue;
8080
}
8181
if (!cost) {

0 commit comments

Comments
 (0)