首页 > web前端 > js教程 > 使用 Javascript 的递归难题

使用 Javascript 的递归难题

王林
发布: 2024-08-17 06:53:08
原创
1082 人浏览过

Recursive Hard Problems Using Javascript

问。如何使用递归找到从主页/源到目的地的方法

“XXXXXEX”,
“××”,

“××××××”

“XXXXXEX”,
“X X X”,
“X X X”,
“X XXX X”,
“××”,
“XSXXXXXX”

从这两种模式中找出从源到目的地的路径

// const maze = [
//     "XXXXXEX",
//     "X     X",
//     "XSXXXXX"
//     ];
const maze = [
    "XXXXXEX",
    "X   X X",
    "X   X X",
    "X XXX X",
    "X     X",
    "XSXXXXXX"
    ];
const dir = [
    [-1, 0],
    [1, 0],
    [0, -1],
    [0, 1]
    ];

visited = {};

path = [];

const findPath = (row, col) => {
    //1. out of bound condition
    if (row < 0 || row >= maze.length || col < 0 || col >= maze[0].length) {
        return false;
    }

    //2. Already visited 
    if (visited[`${row}_${col}`]) {
        return false;
    }


    // found road block 
    if (maze[row][col] === 'X') {
        return false;
    }

    // found the End

    if (maze[row][col] === 'E') {
         path.push(`${row}_${col}`);
        return true;
    }

    path.push(`${row}_${col}`);
    visited[`${row}_${col}`] = true;

    for (let item of dir) {
        const [x, y] = item;
        if (findPath(row+x, col+y)) {
            return true;
        }
    }
    path.pop();
    return false;
};

findPath(5,1);
// findPath(2,1);
console.log(path)

/*
node /tmp/n2GEk3kzOo.js
[
  '5_1', '4_1', '4_2',
  '4_3', '4_4', '4_5',
  '3_5', '2_5', '1_5',
  '0_5'
]
*/
登录后复制

以上是使用 Javascript 的递归难题的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板