728x90
반응형
목차
문제
https://school.programmers.co.kr/learn/courses/30/lessons/49994
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
문제 구현 방향
시작점과 끝점을 합친 문자열을 set에 추가하는 방식으로 진행을 했다. 그 이후에 시작점과 끝점이 서로 바뀐 경우에 대해 빼주는 예외처리를 진행했다.
코드 구현
const direction = { U: [0, 1], D: [0, -1], R: [1, 0], L: [-1, 0] };
const tg = new Set();
function trans(z) {
if (z >= 5) z = 5;
if (z <= -5) z = -5;
return z;
}
function solution(dirs) {
var cnt = 0;
let curX = 0;
let curY = 0;
for (let dr of dirs) {
let [x, y] = direction[dr];
let nX = curX + x;
let nY = curY + y;
nX = trans(nX);
nY = trans(nY);
if (!(curX === nX && curY === nY))
tg.add(`${curX} ${curY}/${nX} ${nY}`);
curX = nX;
curY = nY;
}
let arr = Array.from(tg);
for (let i = 0; i < arr.length; i++) {
let [compFrom, compTo] = arr[i].split("/");
let flag = 1;
for (let j = 0; j < arr.length; j++) {
if (i !== j) {
let [tgFrom, tgTo] = arr[j].split("/");
if (compFrom === tgTo && compTo === tgFrom) {
flag = 0;
break;
}
}
}
if (!flag) cnt++;
}
return arr.length - Math.floor(cnt / 2);
}
더 나은 풀이
set에 추가할 때 방향을 바꿔서 다 추가해주면 그거에 2분의 1을 해주면 더 쉽게 풀 수 있다.
function solution(dirs) {
const directions = {
U : [0,1],
D : [0,-1],
R : [1,0],
L : [-1,0]
}
let x = 0, y = 0
let data = new Set()
for (let dir of dirs) {
const [dx,dy] = directions[dir]
let nx = x + dx
let ny = y + dy
if (nx < -5 || nx > 5 || ny < -5 || ny > 5) continue;
let path1 = `${x},${y},${nx},${ny}`
let path2 = `${nx},${ny},${x},${y}`
data.add(path1)
data.add(path2)
x = nx
y = ny
}
return data.size/2
}반응형
'PS > 프로그래머스' 카테고리의 다른 글
| [프로그래머스][문자열] 뉴스 클러스터링 (0) | 2025.12.06 |
|---|---|
| [프로그래머스][dp] 연속 펄스 부분 수열의 합 (0) | 2025.12.01 |
| [프로그래머스][dfs] 후보키 (0) | 2025.11.26 |
| [프로그래머스][브루트포스] 문자열 압축 (0) | 2025.11.25 |
| [프로그래머스][수학] 2개 이하로 다른 버튼 (0) | 2025.11.19 |