难度中等87
设想有个机器人坐在一个网格的左上角,网格 r 行 c 列。机器人只能向下或向右移动,但不能走到一些被禁止的网格(有障碍物)。设计一种算法,寻找机器人从左上角移动到右下角的路径。
网格中的障碍物和空位置分别用 1
和 0
来表示。
返回一条可行的路径,路径由经过的网格的行号和列号组成。左上角为 0 行 0 列。如果没有可行的路径,返回空数组。
class Solution {
public List<List<Integer>> pathWithObstacles(int[][] obstacleGrid) {
List<List<Integer>> path = new ArrayList<>();
int rows = obstacleGrid.length;
int cols = obstacleGrid[0].length;
boolean[][] visited = new boolean[rows][cols];
dfs(obstacleGrid, 0, 0, visited, path);
return path;
}
//设置visited是为了搜索过的格子不再进行搜索,以