【Leetcode】980. Unique Paths III

题目地址:

https://leetcode.com/problems/unique-paths-iii/

给定一个 m m m n n n列的二维矩阵, 0 0 0代表空地, − 1 -1 1代表障碍物, 1 1 1代表起点, 2 2 2代表终点。问从起点开始走过所有空地到达终点的路径方案数。

可以用DFS + 状态压缩。用一个整型数字的二进制位代表哪些位置已经访问过。代码如下:

class Solution {
 public:
  int uniquePathsIII(vector<vector<int>>& g) {
    int sx, sy, cnt = 0;
    for (int i = 0; i < g.size(); i++)
      for (int j = 0; j < g[0].size(); j++)
        if (g[i][j] == 1) sx = i, sy = j, cnt++;
        else if (!g[i][j]) cnt++;

    int res = 0;
    dfs(sx, sy, 0, cnt, g, res);
    return res;
  }

  void dfs(int x, int y, int vis, int cnt, vector<vector<int>>& g, int& res) {
    if (g[x][y] == 2) {
      if (!cnt) res++;
      return;
    }

    vis |= 1 << x * g[0].size() + y;
    cnt--;
    static int d[] = {-1, 0, 1, 0, -1};
    for (int i = 0; i < 4; i++) {
      int nx = x + d[i], ny = y + d[i + 1];
      if (0 <= nx && nx < g.size() && 0 <= ny && ny < g[0].size()) {
        int nidx = nx * g[0].size() + ny;
        if (!~g[nx][ny] || (vis >> nidx & 1)) continue;
        dfs(nx, ny, vis, cnt, g, res);
      }
    }
  }
};

时间复杂度是指数级,空间 O ( m n ) O(mn) O(mn)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值