leetcode980.不同路径(java):回溯深度优先遍历

题目
在这里插入图片描述
具体代码

class Solution {
    int num;
    public int uniquePathsIII(int[][] grid) {
        int row = grid.length;
        int col = grid[0].length;
        //记录该位置是否走过
        boolean[][] used = new boolean[row][col];
        //记录需要遍历的位置
        int rest = row * col;
        int[] start = new int[2];
        int[] end = new int[2];
        for(int i = 0;i < row;i++){
            for(int j = 0;j < col;j++){
                if(grid[i][j] == -1){
                //有障碍,认为该位置走过,需要遍历的位置数-1.
                    used[i][j] = true;
                    --rest;
                }
                else if(grid[i][j] == 1){
                    start[0] = i;
                    start[1] = j;
                }
                else if(grid[i][j] == 2){
                    end[0] = i;
                    end[1] = j;
                }
            }
        }
        helper(grid,used,rest,start[0],start[1],end);
        return num;
    }
    public void helper(int[][] grid,boolean[][]used,int rest,int x,int y,int[] end){
        if(x == end[0] && y == end[1]){
            if(rest == 1){
                num++;
            }
            return;
        }
        --rest;
        used[x][y] = true;
        //向上
        if(x-1 >= 0 && !used[x-1][y])  helper(grid,used,rest,x-1,y,end);       
        //向下
        if(x+1 < grid.length && !used[x+1][y])  helper(grid,used,rest,x+1,y,end);
        //向左
        if(y-1 >= 0 && !used[x][y-1])  helper(grid,used,rest,x,y-1,end);
        //向右
        if(y+1 < grid[0].length && !used[x][y+1])  helper(grid,used,rest,x,y+1,end);
        used[x][y] = false;
        rest++;
    }
}

参考题解

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值