using PII = pair<int, int>;
class Solution {
private:
static constexpr int dx[4] = {0, 0, 1, -1};
static constexpr int dy[4] = {1, -1, 0, 0};
public:
int minCost(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<int> dist(m * n, 0x3f3f3f3f);
vector<bool> st(m * n, false);
priority_queue<PII, vector<PII>, greater<PII>> heap;
dist[0] = 0;
heap.emplace(0, 0);
while (!heap.empty()) {
auto [distance, vertex] = heap.top();
heap.pop();
if (st[vertex]) continue;
st[vertex] = true;
int x = vertex / n, y = vertex % n;
for (int i = 0; i < 4; i++) {
int newX = x + dx[i];
int newY = y + dy[i];
int newVertex = newX * n + newY;
int newDistance = distance + (grid[x][y] != i + 1);
if (newX >= 0 && newX < m && newY >= 0 && newY < n && newDistance < dist[newVertex]) {
dist[newVertex] = newDistance;
heap.emplace(newDistance, newVertex);
}
}
}
return dist[m * n - 1];
}
};