문제출처
const findValue = (visit, target) => {
const filtered = visit.filter(v => JSON.stringify(v) === JSON.stringify(target));
return filtered.length === 0 ? false : true;
}
function solution(dirs) {
let answer = 0;
const visit = [];
let now = [0, 0];
for (let i=0; i<dirs.length; i++) {
if (dirs[i] === 'U') {
if (now[1] + 1 > 5) continue;
now = [now[0], now[1] + 1];
if (findValue(visit, [now, [now[0], now[1]-1]]) || findValue(visit, [[now[0], now[1]-1], now])) continue;
visit.push([now, [now[0], now[1]-1]]);
} else if (dirs[i] === 'D') {
if (now[1] - 1 < -5) continue;
now = [now[0], now[1] - 1];
if (findValue(visit, [now, [now[0], now[1]+1]]) || findValue(visit, [[now[0], now[1]+1], now])) continue;
visit.push([now, [now[0], now[1]+1]]);
} else if (dirs[i] === 'R') {
if (now[0] + 1 > 5) continue;
now = [now[0] + 1, now[1]];
if (findValue(visit, [now, [now[0]-1, now[1]]]) || findValue(visit, [[now[0]-1, now[1]], now])) continue;
visit.push([now, [now[0]-1, now[1]]]);
} else {
if (now[0] - 1 < -5) continue;
now = [now[0] - 1, now[1]];
if (findValue(visit, [now, [now[0]+1, now[1]]]) || findValue(visit, [[now[0]+1, now[1]], now])) continue;
visit.push([now, [now[0]+1, now[1]]]);
}
answer++;
}
return answer;
}