1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { using TII = tuple<int, int, int>; public: int minCost(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(), ds[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; vector<vector<int>> dist(m, vector<int>(n, 0x3f3f3f3f)); vector<vector<bool>> vis(m, vector<bool>(n)); dist[0][0] = 0; priority_queue<TII, vector<TII>, greater<TII>> q; q.emplace(0, 0, 0); while (q.size()) { auto [d, x, y] = q.top(); q.pop(); if (vis[x][y]) continue; vis[x][y] = true; for (int i = 0; i < 4; ++i) { int nx = x + ds[i][0], ny = y + ds[i][1]; if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue; int w = grid[x][y] != i + 1; if (dist[nx][ny] > dist[x][y] + w) { dist[nx][ny] = dist[x][y] + w; q.emplace(dist[nx][ny], nx, ny); } } } return dist[m - 1][n - 1]; } };
|