lc490

https://xiaoguan.gitbooks.io/leetcode/content/LeetCode/490-the-maze-medium.html

[algorithm]
1 what is graph? what is edge? what is node?
2 write dfs pseudo
3 move() method, what is relevant to this move, make it as param.
on high level, use move() as block.

[code]

int[] dirs = [[-1,0], [1,0], [0,-1], [0,1]];
int[][] grid;
int w, h;

boolean canReach(int[][] grid, int[] sta, int[] end){
    
    this.gid = grid;
    this.w = grid[0].length;
    this.h = grid.length;

    List<Integer> path = new ArrayList<>(); 
    dfs(sta, end, path, succ);
    return succ[0];
}


void dfs(int[] cur, int[] end, Set path, boolean[] succ){
    
    if(bound(cur)){ //false
        return;
    }
    if(visited[x][y]==true){ //skip
        return;
    }
    if(path.contains(y*w+x)){ //loop, false
        return;
    }
    if(x==end[0] && y==end[1]){
        succ[0] = true;
        return;
    }
    path.add(y*w+x);
    for(int[] dir: dirs){
        if(move(dir, cur, neigh)==false){
            continue;
        }
        dfs(neigh, end, path, succ);
    }
    path.remove(y*w+x);
}

boolean bound(int[] cur){
    
    int x = cur[0];
    int y = cur[1]; 
    return x<0 || x>w || y<0 || y>h; 
}

boolean move(dir, src, dst){
    
    int x = src[0] + dir[0];
    int y = src[1] + dir[1];
    while(grid[x][y]!=0 && bound(new int[2]{x,y})){
        x += dir[0];
        y += dir[1];
    }
    return !bound(new int[2]{x,y}); //false if bound    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值