const park = ["OSO", "OOO", "OXO", "OOO"];
const routes = ["E 2", "S 3", "W 1"];
function solution(park, routes) {
let answer = [];
let map = park.map((dir) => dir.split(""));
let startPos = [];
// 방향 배열
let dir = [
[-1, 0],
[0, 1],
[1, 0],
[0, -1],
];
// 시작점 구하기
for (let i = 0; i < map.length; i++) {
for (let j = 0; j < map[0].length; j++) {
if (map[i][j] === "S") {
startPos.push(i, j);
break;
}
}
}
for (let i = 0; i < routes.length; i++) {
let [direction, dirNum] = [
routes[i].split(" ")[0],
Number(routes[i].split(" ")[1]),
];
// 이동 횟수를 저장할 count 변수
let count = 0;
if (direction === "E") {
while (dirNum !== 0) {
let nx = startPos[0] + dir[1][0];
let ny = startPos[1] + dir[1][1];
if (
nx < 0 ||
ny < 0 ||
nx >= map.length ||
ny >= map[0].length ||
map[nx][ny] === "X"
) {
startPos[0] = startPos[0];
startPos[1] = startPos[1] + count * -1;
count = 0;
break;
} else {
startPos = [nx, ny];
count++;
dirNum--;
}
}
} else if (direction === "S") {
while (dirNum !== 0) {
let nx = startPos[0] + dir[2][0];
let ny = startPos[1] + dir[2][1];
if (
nx < 0 ||
ny < 0 ||
nx >= map.length ||
ny >= map[0].length ||
map[nx][ny] === "X"
) {
startPos[0] = startPos[0] + count * -1;
startPos[1] = startPos[1];
count = 0;
break;
} else {
startPos = [nx, ny];
count++;
dirNum--;
}
}
} else if (direction === "W") {
while (dirNum !== 0) {
let nx = startPos[0] + dir[3][0];
let ny = startPos[1] + dir[3][1];
if (
nx < 0 ||
ny < 0 ||
nx >= map.length ||
ny >= map[0].length ||
map[nx][ny] === "X"
) {
startPos[0] = startPos[0];
startPos[1] = startPos[1] + count;
count = 0;
break;
} else {
startPos = [nx, ny];
count++;
dirNum--;
}
}
} else if (direction === "N") {
while (dirNum !== 0) {
let nx = startPos[0] + dir[0][0];
let ny = startPos[1] + dir[0][1];
if (
nx < 0 ||
ny < 0 ||
nx >= map.length ||
ny >= map[0].length ||
map[nx][ny] === "X"
) {
startPos[0] = startPos[0] + count;
startPos[1] = startPos[1];
count = 0;
break;
} else {
startPos = [nx, ny];
count++;
dirNum--;
}
}
}
}
return startPos;
}
console.log(solution(park, routes));
여기서 핵심은 이동을 하다가 공원 범위를 벗어나거나 장애물을 만났을때 다시 그만큼 회귀해야하는점이다.
그렇기 때문에 이동 횟수를 저장할 count 배열을 하나 만들어주어야한다.
만약에 시작점이 [0, 1]인데 E 2 인 경우, [0, 2]까지는 이동이 가능하지만 [0, 3]이 되는 순간 시작점을 다시 [0,1]으로 돌려야하므로 count에 그값을 저장해준 다음에 그 값을 다시 빼주어서 시작점을 초기화 시켜준다.