回溯迷宫找终点

迷宫找出口

image

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));

posted @ 2019-05-17 23:16  pluscat  阅读(181)  评论(0编辑  收藏  举报