프로그래머스 - 거리두기 확인하기(Level 2)
2023. 12. 28. 17:24ㆍ코딩테스트 정리(자바)
728x90
public class 거리두기 {
public static final int[] dx = {0, -1, 1, 0}; //상, 좌, 우, 하
public static final int[] dy = {-1, 0, 0, 1}; //상, 좌, 우, 하
public boolean isNextToVolunteer(char[][] room, int x, int y, int exclude) {
for (int d = 0; d < 4; d++) {
if (d == exclude) continue; //전에 검사한쪽의 반대 방향은 검사안함
int nx = x + dx[d];
int ny = y + dy[d];
if (ny < 0 || ny >= room.length || nx < 0 || nx >= room[ny].length) //범위 넘어가는지 체크
continue;
if (room[ny][nx] == 'P') return true; //P가 있다면 true 반환
}
return false;
}
public boolean isDistanced(char[][] room, int x, int y) {
for (int d = 0; d < 4; d++) {
int nx = x + dx[d];
int ny = y + dy[d];
if (ny < 0 || ny >= room.length || nx < 0 || nx >= room[ny].length) //범위 넘어가는지 체크
continue;
switch (room[ny][nx]) {
case 'P': return false; //P옆에 바로 P이면 false
case 'O':
if (isNextToVolunteer(room, nx, ny, 3- d)) return false;
//P옆에 O라면 그 옆에 P가 있는지 검사, 반대방향은 검사안하기 위해 3-d 넘겨줌
}
}
return true;
}
public boolean isDistanced(char[][] room) {
for (int y = 0; y < room.length; y++) {
for (int x = 0; x < room[y].length; x++) {
if (room[y][x] != 'P') continue; //P인 것만 관심있음
if (!isDistanced(room, x, y)) return false; //P옆에 뭐가 있나 검사
}
}
return true;
}
public int[] solution(String[][] places) {
int[] answer = new int[places.length]; //places의 행 길이만큼 크기 지정
for (int i = 0; i < answer.length; i++) { //대기실 하나를 char[][] 타입으로 변경하기
String[] place = places[i];
char[][] room = new char[place.length][];
for (int j = 0; j < room.length; j++) {
room[j] = place[j].toCharArray();
}
if (isDistanced(room)) { //거리 2 넘어가는지 검사
answer[i] = 1;
} else {
answer[i] = 0;
}
}
return answer;
}
}
1. return false하면 반복문 종료되며 false 반환
2.
switch (room[ny][nx]) {
case 'P': return false; //P옆에 바로 P이면 false
case 'O':
if (isNextToVolunteer(room, nx, ny, 3- d))
return false;
//P옆에 O라면 그 옆에 P가 있는지 검사, 반대방향은 검사안하기 위해 3-d 넘겨줌
}
switch의 각 case문은 괄호로 안감싸도 됨
3.
char[][] ch=new char[str.length][];
행만 크기 지정할 수 있음
728x90
'코딩테스트 정리(자바)' 카테고리의 다른 글
| 프로그래머스 - 이상한 문자 만들기 (Level 1) (0) | 2023.12.30 |
|---|---|
| 프로그래머스 - 시저 암호 (Level 1) (0) | 2023.12.28 |
| 프로그래머스 - 자연수 뒤집어 배열로 만들기 (Level 1) (2) | 2023.12.25 |
| 프로그래머스 - 행렬의 곱셈 (Level 2) (3) | 2023.12.23 |
| 프로그래머스 - 삼각 달팽이 (Level 2) (2) | 2023.12.22 |