my
#include <deque> #include <iostream> #include <tuple> #include <unordered_map> #include <vector> typedef array<int, 3> AI3; using namespace std; class Solution { public: int minCost(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); unordered_map<int, pair<int, int>> direct = {// 右 左 下 上 {1, make_pair(0, 1)}, {2, make_pair(0, -1)}, {3, make_pair(1, 0)}, {4, make_pair(-1, 0)}}; vector<vector<bool>> visit(grid.size(),vector<bool>(grid[0].size(), false)); visit[0][0] = true; priority_queue<AI3, vector<AI3>, greater<>> pq; pq.push({0, 0, 0}); visit[0][0] = true; while (!pq.empty()) { auto [cost, i, j] = pq.top(); pq.pop(); if (i == (m - 1) && j == (n - 1)) return cost; for (const auto& p : direct) { int x = i + p.second.first; int y = j + p.second.second; if (x < 0 || x >= m || y < 0 || y >= n || visit[x][y]) continue; int addon = (grid[i][j] == p.first) ? 0 : 1; pq.push({cost + addon, x, y}); } visit[i][j] = true; } return -1; } };
Leave a Comment