minimum-cost-to-make-at-least-one-valid-path-in-a-grid 1.0.0
Minimum Cost to Make at Least One Valid Path in a Grid
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
6{
7 template <class T1, class T2>
8 std::size_t operator()(const std::pair<T1, T2>& p) const
9 {
10 auto hash1 = std::hash<T1>{}(p.first);
11 auto hash2 = std::hash<T2>{}(p.second);
12 return hash1 ^ hash2;
13 }
14};
15
17{
18public:
19 int minCost(vector<vector<int>>& grid)
20 {
21 unordered_map<int, pair<int, int>> direction; // direction num, (row, column)
22 direction[1] = {0, 1};
23 direction[2] = {0, -1};
24 direction[3] = {1, 0};
25 direction[4] = {-1, 0};
26
27 int rows = (int)grid.size(), cols = (int)grid[0].size();
28 deque<tuple<int, int, int>> q; // (row, column, cost)
29 q.push_back({0, 0, 0}); // upper left corner
30
31 unordered_map<pair<int, int>, int, pair_hash> min_cost;
32 min_cost[{0, 0}] = 0;
33
34 while (!q.empty())
35 {
36 auto [row, col, cost] = q.front();
37 q.pop_front();
38
39 if (row == rows - 1 && col == cols - 1)
40 return cost;
41
42 for (auto dir: direction) // dir is a (key, value), where key is 1-4 and value is (row, col)
43 {
44 auto [d_row, d_col] = dir.second;
45 int n_row = d_row + row;
46 int n_col = d_col + col;
47
48 int n_cost = cost;
49 if (dir.first != grid[row][col])
50 n_cost++;
51
52 if (n_row < 0 || n_col < 0 || n_row >= rows || n_col >= cols || (min_cost.find({n_row, n_col}) != min_cost.end() && n_cost >= min_cost[{n_row, n_col}]))
53 continue;
54
55 min_cost[{n_row, n_col}] = n_cost;
56 if (dir.first == grid[row][col])
57 q.push_front({n_row, n_col, n_cost});
58 else
59 q.push_back({n_row, n_col, n_cost});
60 }
61 }
62 return min_cost[{rows - 1, cols - 1}];
63 }
64};
65
66int main()
67{
68 vector<vector<int>> grid = {{1,1,1,1}, {2,2,2,2}, {1,1,1,1}, {2,2,2,2}};
69 cout << Solution().minCost(grid) << '\n';
70 return 0;
71}
int minCost(vector< vector< int > > &grid)
Definition main.cpp:19
int main()
Definition main.cpp:66
std::size_t operator()(const std::pair< T1, T2 > &p) const
Definition main.cpp:8