Algorithm/Programmers Java
[JAVA] 프로그래머스 LEVEL2 거리두기 확인하기
제우제우
2024. 10. 13. 02:00
https://school.programmers.co.kr/learn/courses/30/lessons/81302
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
코딩테스트 연습 > 2021 카카오 채용연계형 인턴십 > 거리두기 확인하기
난이도: LEVEL2
알고리즘 유형: BFS
정답 코드
import java.util.*;
class Solution {
static int [] arx = {-1,1,0,0};
static int [] ary = {0,0,-1,1};
static int [] answer;
public int[] solution(String[][] places) {
answer = new int [places.length];
for(int i = 0; i < places.length; i++){
test(i, places[i]);
}
return answer;
}
public static void test(int index, String [] place){
boolean flag = true;
Queue<int []> q = new LinkedList<>();
int [][] map = new int [5][5];
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
char cur = place[i].charAt(j);
if(cur == 'X') map[i][j] = -1; // 파티션
if(cur == 'P'){
map[i][j] = 1; // 사람
q.add(new int [] {i, j, i, j, 0});
}
}
}
while(!q.isEmpty()){
int [] cur = q.poll();
if(cur[4] == 2) continue;
for(int i = 0; i < 4; i++){
int nx = arx[i] + cur[0];
int ny = ary[i] + cur[1];
// ArrayOut || 시작 위치 || 파티션
if(!validation(nx, ny) || (nx == cur[2] && ny == cur[3]) || map[nx][ny] == -1){
continue;
}
if(map[nx][ny] == 1){
return;
}
q.add(new int [] {nx, ny, cur[2], cur[3], cur[4] + 1});
}
}
answer[index] = 1;
}
public static boolean validation(int nx, int ny){
if(0 <= nx && 0 <= ny && nx < 5 && ny < 5) return true;
return false;
}
}