Q. 재귀를 이용하여 집으로 가는 길/목적지까지 가는 방법
"XXXXXEX",
"엑스엑스",
"XXXXXEX",
"X X X",
"X X X",
"엑스XXX엑스",
"엑스엑스",
"XSXXXXXX"
이 2가지 패턴에서 소스에서 대상까지의 경로를 알아보세요
// 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!