https://school.programmers.co.kr/learn/courses/30/lessons/49994
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
⭐️ 중요 포인트
1. Point와 Edge의 equlas()와 hashCode()를 직접 구현하기
(기존의 equals()를 사용하게 되면 내부 값이 같은지 비교하는 것이 아니라 클래스의 주소 값이 같은지(같은 클래스인지) 비교하게 된다.)
2. Edge는 방향성이 없으므로 hashCode를 p1과 p2의 합으로 두면 방향이 같아도 서로 같은 edge(객체)라고 인식해 중복을 없앨 수 있다.
3. isInRange()로 게임 캐릭터가 다음 움직일 칸이 맵 안쪽(유효한 x, y 좌표값)인지 확인하며 dirs를 순환한다.
-> equlas()와 hashCode()의 오버라이드 기본형태 알아두기
import java.util.*;
class Solution {
static class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
/*
1. equlas()는 항상 Object를 받음
2. instnaceof를 통해 타입 확인
3. 형변환
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point other = (Point) obj;
if (this.x == other.x && this.y == other.y) {
return true;
}
return false;
};
/*
1. hashCode()는 매개변수가 없음
2. (일반적인 방법) Object.hash(해시 펑션에 넣을 내부 값)을 통해 해시펑션 돌림
*/
@Override
public int hashCode() {
return Objects.hash(this.x, this.y);
}
}
static class Edge {
Point p1;
Point p2;
Edge(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Edge)) {
return false;
}
Edge other = (Edge) obj;
if (p1.equals(other.p1) && p2.equals(other.p2) || p1.equals(other.p2) && p2.equals(other.p1)) {
return true;
}
return false;
}
@Override
public int hashCode() {
return p1.hashCode() + p2.hashCode();
}
}
static String dirs;
static int answer;
static Set<Edge> s;
void init(String dirs) {
this.dirs = dirs;
this.answer = 0;
this.s = new HashSet<>();
}
boolean isInRange(int x, int y) {
if (-5 <= x && x <= 5 && -5 <= y && y <= 5) {
return true;
}
return false;
}
void solve() {
int curX = 0;
int curY = 0;
for (char c: dirs.toCharArray()) {
int dx = 0;
int dy = 0;
if (c == 'U') {
dy = -1;
} else if (c == 'D') {
dy = 1;
} else if (c == 'R') {
dx = 1;
} else if (c == 'L') {
dx = -1;
}
int nextX = curX + dx;
int nextY = curY + dy;
if (isInRange(nextX, nextY)) {
s.add(new Edge(new Point(curX, curY), new Point(nextX, nextY)));
curX = nextX;
curY = nextY;
}
}
answer = s.size();
}
public int solution(String dirs) {
init(dirs);
solve();
return answer;
}
}
'프로그래머스 알고리즘 > Java' 카테고리의 다른 글
[프로그래머스] 점프와 순간 이동 - Java (0) | 2025.06.11 |
---|---|
[프로그래머스] 연속 부분 수열 합의 개수 - Java (1) | 2025.05.13 |
[프로그래머스] 최솟값 만들기 - Java (0) | 2025.05.12 |
[프로그래머스] 자연수 뒤집어 배열로 만들기 - Java (0) | 2025.05.12 |
[프로그래머스] 2 x n 타일링 - Java (0) | 2025.05.08 |