20 {
21 unordered_map<int, pair<int, int>> direction;
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;
29 q.push_back({0, 0, 0});
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)
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 }