알고리즘
Robot Paths (feat.로봇청소기야 너 굉장히 고생하고 있었구나 ㅠㅠ)
Hot Dobby
2020. 10. 31. 02:24
Q. 맨 위 왼쪽 모서리에 있는 로봇이, 맨 아래 오른쪽 모서리로 이동하려고 합니다.
로봇은 위, 아래, 왼쪽, 오른쪽으로 이동할 수 있지만, 같은 장소를 두 번 방문할 수는 없습니다.
로봇이 맨 아래 오른쪽 모서리로 이동할 수 있는 경로의 총 가짓수를 구해 보세요. 경로에 중복이 있어선 안 됩니다!
const makeBoard = function (n) {
let board = [];
for (let i = 0; i < n; i++) {
board.push([]);
for (let j = 0; j < n; j++) {
board[i].push(false);
}
}
board.togglePiece = function (i, j) {
this[i][j] = !this[i][j];
};
board.hasBeenVisited = function (i, j) {
return !!this[i][j];
};
return board;
};
const robotPaths = function (n, board, i, j) {
board = makeBoard(n);
let count = 0;
function recurse(x, y, z) {
if(x === n - 1 && y === n - 1) {
count++;
return;
}
if(z> 1000){
return;
}
board.togglePiece(x, y);
if(x >= 0 && x < n && y + 1 >= 0 && y + 1 < n && !board.hasBeenVisited(x, y + 1)) {
recurse(x, y + 1, z+1);
}
if(x + 1 >= 0 && x + 1 < n && y >= 0 && y < n && !board.hasBeenVisited(x + 1, y)) {
recurse(x + 1, y, z+1);
}
if(x >= 0 && x < n && y - 1 >= 0 && y - 1 < n && !board.hasBeenVisited(x, y - 1)) {
recurse(x, y - 1, z+1);
}
if(x - 1 >= 0 && x - 1 < n && y >= 0 && y < n && !board.hasBeenVisited(x - 1, y)) {
recurse(x - 1, y, z+1);
}
board.togglePiece(x, y,);
return;
}
recurse(0, 0, 0);
return count;
}