





풀이
은찬
function solution(dirs) { let answer = 0; const map = new Map(); const direct = [[-1, 0], [1, 0], [0, -1], [0, 1]]; const queue = []; let x = 5; let y = 5; const rangeCheck = (x) => { if(x < 0){ return 0; } else if(x > 10){ return 10; } return x; } for(let i = 0; i < dirs.length; i++){ let go = `${x}${y}`; let back = `${x}${y}`; const cx = x; const cy = y; if(dirs[i] === "U"){ x = rangeCheck(x + direct[0][0]); y = rangeCheck(y + direct[0][1]); } else if(dirs[i] === "D"){ x = rangeCheck(x + direct[1][0]); y = rangeCheck(y + direct[1][1]); } else if(dirs[i] === "L"){ x = rangeCheck(x + direct[2][0]); y = rangeCheck(y + direct[2][1]); } else if(dirs[i] === "R"){ x = rangeCheck(x + direct[3][0]); y = rangeCheck(y + direct[3][1]); } if(cx !== x || cy !== y){ go = `${go}${x}${y}`; back = `${x}${y}${back}`; if(!map.has(go) || !map.has(back)){ answer++; map.set(go, true); map.set(back, true); } } } return answer; }
재영
const solution = (dirs) => { const directions = { U: [0, -1], L: [-1, 0], D: [0, 1], R: [1, 0] }; let answer = 0; // 결과 값 const visited = new Set(); // 방문 여부 let x = 0; let y = 0; [...dirs].forEach(dir => { const [dx, dy] = directions[dir]; // 방향에 따른 변경 x, y const nx = x + dx; const ny = y + dy; const stringifiedVisitedEdge = JSON.stringify([x, y, nx, ny]); const checkVisitedValues = [ stringifiedVisitedEdge, // a -> b JSON.stringify([nx, ny, x, y]) // b -> a ] if (nx > 5 || nx < -5 || ny > 5 || ny < -5 ) return; // 1번째 조건 x = nx; y = ny; // Array.every -> 모든 게 true(all) -> true // Array.some -> 1개라도 true (any) -> true if (!checkVisitedValues.some(value => visited.has(value))) { visited.add(stringifiedVisitedEdge) answer += 1; } }) return answer; }
효성
function solution(dirs) { let answer = 0, now = [0, 0]; const move = { L: [-1, 0], R: [1, 0], U: [0, 1], D: [0, -1] }; let route = new Set(); const canGo = (x, y) => { if (x > 5 || x < -5 || y > 5 || y < -5) return false; else return true; } for (let dir of dirs) { let nowX = now[0] + move[dir][0]; let nowY = now[1] + move[dir][1]; if(!canGo(nowX, nowY)) { continue; } route.add("" + now[0] + now[1] + nowX + nowY); route.add("" + nowX + nowY + now[0] + now[1]); now = [nowX, nowY]; } return route.size / 2; }