首頁 >web前端 >js教程 >使用 Javascript 的遞歸難題

使用 Javascript 的遞歸難題

王林
王林原創
2024-08-17 06:53:081082瀏覽

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