Lewis's Tech Keep
[프로그래머스] 방문 길이 본문
- 간선 맵 생성 (edgeMap)
- 각 간선 맵에 맞는 index를 좌표를 기반으로 하여 대입 (1:1 mapping 가능하게 함)
- 각 간선 체크
- 완료
피드백
- 좋지 않은 이유 : 공식 세우는 데만 6시간 이상 걸려버렸다.. 이럴 만한 이유까지는 없었는데..
- 클래스로 생성 후 비교 시 좀 더 깔끔하게 마무리 가능하다.
더보기
import java.util.*;
class Solution {
public int solution(String dirs) {
int answer = 0;
int lineCount = 11; // 11 * 11 line
int cellCount = lineCount - 1; // 11줄 -> 10칸
int totalLineCount = lineCount * cellCount * 2; // (11 * 10) * 2 : 220 line
boolean[] edgeMap = new boolean[totalLineCount];
// 1칸씩 움직일 때 mapping formula
// 여기서 lineCount = 전체 line 숫자
// 여기서 x2, y2 -> 좌표 이동 후, x1, y1 -> 좌표 이동 전
// U y edge 공식 : totalLineCount / 2 (= 카운트 절반) + cellCount * x2 + cellCount-y2;
// D y edge 공식 : totalLineCount / 2 (= 카운트 절반) + cellCount * x2 + cellCount-y1;
// L x edge 공식 : cellCount * (cellCount-y2) + x2;
// R x edge 공식 : cellCount * (cellCount-y2) + x1;
Map<String, Integer> dMap = new HashMap<>(); // directionMap
dMap.put("U", 1);
dMap.put("D", -1);
dMap.put("L", -1);
dMap.put("R", 1);
int dx = 5;
int dy = 5;
String[] dirsArr = dirs.split("");
for(String dir: dirsArr) {
int move = dMap.get(dir);
int cx = dx;
int cy = dy;
int edgeIdx = -1;
if(dir.equals("U")) {
if(dy >= 0 && dy < 10) {
dy += move;
edgeIdx = totalLineCount / 2 + cellCount * dx + cellCount-dy;
}
} else if (dir.equals("D")) {
if(dy > 0 && dy <= 10) {
dy += move;
edgeIdx = totalLineCount / 2 + cellCount * dx + cellCount-cy;
}
} else if(dir.equals("L")) {
if(dx > 0 && dx <= 10) {
dx += move;
edgeIdx = cellCount * (cellCount-dy) + dx;
}
} else if(dir.equals("R")) {
if(dx >= 0 && dx < 10) {
dx += move;
edgeIdx = cellCount * (cellCount-dy) + cx;
}
}
if(edgeIdx != -1 && !edgeMap[edgeIdx]) {
// 엣지 mapping 가능
edgeMap[edgeIdx] = true;
answer++;
}
};
return answer;
}
}
'Java > 알고리즘' 카테고리의 다른 글
[프로그래머스] N으로 표현 (0) | 2021.02.08 |
---|---|
[프로그래머스] 방문 길이 ( 2 try) (0) | 2021.02.06 |
[프로그래머스] H-Index (0) | 2021.02.03 |
[프로그래머스] 여행 경로 (0) | 2021.02.02 |
[프로그래머스] 단어 변환 (0) | 2021.02.01 |
Comments