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
Solution Class Reference

Public Member Functions

int minCost (vector< vector< int > > &grid)
 

Detailed Description

Definition at line 16 of file main.cpp.

Member Function Documentation

◆ minCost()

int Solution::minCost ( vector< vector< int > > &  grid)
inline

Definition at line 19 of file main.cpp.

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 }

Referenced by main().


The documentation for this class was generated from the following file: