回溯迷宫找终点

迷宫找出口

回溯迷宫找终点

function isSafe(maze,x,y){
    if(x >= 0 && y >= 0 && x < maze.length && y < maze.length && maze[x][y] !== 0){
        return true
    }
    return false
}

function findPath(maze,solution,x,y){
    if( x === solution.length - 1 && y === solution[0].length - 1){
        solution[x][y] = 1
        return true
    }

    if(isSafe(maze,x,y)){
        solution[x][y] = 1
        if(findPath(maze,solution,x + 1,y)){
            return true
        }
        if(findPath(maze,solution,x, y + 1)){
            return true
        }
        solution[x][y] = 0
    }

    return false
}

function ratInAMaze(maze){
    let solution = []
    for(let i = 0; i < maze.length; i++){
        solution[i] = []
        for(let j = 0; j < maze[0].length; j++){
            solution[i][j] = 0
        }
    }
    
    if(findPath(maze,solution,0,0)){
        return solution
    }

    return 'not solution exsit'
}

const maze = [
    [1, 0, 0, 0],
    [1, 1, 1, 1],
    [0, 0, 1, 0],
    [0, 1, 1, 1]
  ];
  
console.log(ratInAMaze(maze));
上一篇:为物联网代码安全而生 网易易盾公测IoT安全编译器Maze


下一篇:leetcood学习笔记-79-单词搜索