LeetCode 1368. 使网格图至少有一条有效路径的最小代价

LeetCode 1368. 使网格图至少有一条有效路径的最小代价
在这里插入图片描述
思路 : 箭头方向和搜索方向相同,代价为0, 不同代价为1
Dijkstra

const int N = 110;
typedef array<int, 3> AI3; // 表示cost,x, y
class Solution {
public:
    int dx[5] = {0, 0, 0, 1, -1}, dy[5] = {0, 1, -1, 0, 0};
    vector<vector<int>> g;
    bool st[N][N] = {false};
    int dijkstra()
    {
        int n = g.size(), m = g[0].size();
        priority_queue<AI3, vector<AI3>, greater<AI3>> heap;
        heap.push({0, 0, 0});
        while(!heap.empty())
        {
            auto[c, x, y] = heap.top();
            heap.pop();
            if(st[x][y]) continue;
            if(x == n - 1 && y == m - 1) return c;
            st[x][y] = true;
            for(int i = 1; i <= 4; i ++)
            {
                int a = x + dx[i], b = y + dy[i];
                if(a < 0 || a >= n || b < 0 || b >= m || st[a][b]) continue;
                if(i == g[x][y]) // 方向与箭头方向相同
                    heap.push({c, a, b});
                else 
                    heap.push({c + 1, a, b});
            }
        }
        return -1;
    }
    int minCost(vector<vector<int>>& grid) {
        g = grid;
        return dijkstra();
    }
};

0 - 1 BFS

const int N = 110, M = N * N;
typedef pair<int, int> PII; // 表示x, y
class Solution {
public:
    int dx[5] = {0, 0, 0, 1, -1}, dy[5] = {0, 1, -1, 0, 0};
    vector<vector<int>> g;
    bool st[N][N] = {false};
    int dist[N][N];
    int get(int x)
    {
        return (x + M) % M;
    }
    int bfs() // 0-1 BFS ,优化dijkstra
    {
        memset(dist, 0x3f, sizeof dist);
        int n = g.size(), m = g[0].size();
        PII q[M]; int tt = 0, hh = 0;
        q[tt ++] = {0, 0};
        dist[0][0] = 0;
        while(hh != tt)
        {
            auto[x, y] = q[hh];
            hh = get(hh + 1);

            if(st[x][y]) continue;
            if(x == n - 1 && y == m - 1) return dist[x][y];
            st[x][y] = true;
            for(int i = 1; i <= 4; i ++)
            {
                int a = x + dx[i], b = y + dy[i];
                if(a < 0 || a >= n || b < 0 || b >= m || st[a][b]) continue;
                if(dist[a][b] < dist[x][y] + (i != g[x][y])) continue;
                if(i == g[x][y]) // 方向与箭头方向相同
                    hh = get(hh - 1), q[hh] = {a, b}, dist[a][b] = dist[x][y];
                else 
                    q[tt] = {a, b}, dist[a][b] = dist[x][y] + 1, tt = get(tt + 1);
            }
        }
        return -1;
    }
    int minCost(vector<vector<int>>& grid) {
        g = grid;
        return bfs();
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值