题目要求
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,