【leetcode -C++】-DFS类型- 980 unique path 3

题目要求

On a 2-dimensional grid, there are 4 types of squares:

  • 1 represents the starting square.  There is exactly one starting square.
  • 2 represents the ending square.  There is exactly one ending square.
  • 0 represents empty squares we can walk over.
  • -1 represents obstacles that we cannot walk over.

Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly 

数据范围:

1 <= grid.length * grid[0].length <= 20

给定一个二维矩阵,矩阵元素为1的位置是入口,元素为2的是出口,0代表可以走的位置,-1代表障碍。

返回从入口走向出口的不同方案(求解从起点到终点有效路径个数),要求非障碍位置(非-1位置)都必须走过,并且一条路径不能重复走某一个节点。

思路解析

本题首先要遍历矩阵,判断入口出口的位置以及可以走的位置有多少个。

1、dfs回溯

本题可以用dfs暴力搜索来求解,对于当前可落脚的位置,锁定当前位置为障碍位置,并向上、下、左、右四个方向继续走,之后记得还原当前位置。dfs递归的返回条件包括:当前位置为障碍或者这条路径走过的节点;当前位置到达终点。

时间复杂度:O(),空间复杂度O(R*Q)

代码实现

class Solution {
public:
    int res = 0;int ex,ey,sx,sy,m,
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值