문제 :
https://school.programmers.co.kr/learn/courses/30/lessons/169198
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
접근 :
- 4개의 벽면에 대해서 쿠션을한 이동거리가 최소가 되는 길이를 찾는다.
- 공에 외력이 없이 직선으로 힘이 가해진다면 입사각과 반사각이 같으므로, 시작하는 지점으로 부터 해당 벽면을 기준으로 대칭인 지점의 좌표의 길이를 구하면 이동거리가 된다.
- 만약 x나, y의 좌표가 같아 직선으로 바로 이동하는 경우에는 쿠션을 할 수 없으므로 해당 경우는 제외한다.
- 코드 구현 :
class Solution {
private class Position{
int x;
int y;
public Position(int x, int y){
this.x = x;
this.y = y;
}
}
private int calDist(int sx, int sy, int tx, int ty){
int a = sx - tx;
int b = sy - ty;
return (a*a) + (b*b);
}
public int getMinDistance(Position white, Position target, Position end) {
int res = Integer.MAX_VALUE;
// 좌
if (!(white.y == target.y && white.x >= target.x))
res = Math.min(res, calDist(white.x, white.y, target.x * (-1), target.y));
// 우
if (!(white.y == target.y && white.x <= target.x))
res = Math.min(res, calDist(white.x, white.y, 2* end.x - target.x, target.y));
// 상
if (!(white.x == target.x && white.y <= target.y))
res = Math.min(res, calDist(white.x, white.y, target.x, 2*end.y - target.y));
// 하
if (!(white.x == target.x && white.y >= target.y))
res = Math.min(res, calDist(white.x, white.y, target.x, target.y * (-1)));
return res;
}
public int[] solution(int m, int n, int startX, int startY, int[][] balls) {
int[] answer = new int[balls.length];
Position white = new Position(startX, startY);
Position end = new Position(m,n);
for(int i = 0 ; i < balls.length ; i++){
answer[i] = getMinDistance(white, new Position(balls[i][0], balls[i][1]), end);
}
return answer;
}
}
'JAVA > Coding Test' 카테고리의 다른 글
[JAVA] 프로그래머스 베스트앨범_해쉬 (1) | 2024.10.16 |
---|---|
[JAVA] 프로그래머스 이중우선순위큐_힙 (0) | 2024.10.15 |
[JAVA] 프로그래머스 유사 칸토어 비트열_분할정복 (1) | 2024.10.10 |
[JAVA] 프로그래머스 양궁대회_구현 (2) | 2024.09.25 |
[JAVA] 프로그래머스 이모티콘 할인행사_구현 (2) | 2024.09.25 |