programmers_미로 탈출_java
2023. 3. 28. 15:43ㆍAlgorithm/Programmers
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/159993
import java.util.*;
class Solution {
private static int[][] delta = {{0,1}, {1, 0}, {0, -1}, {-1,0}};
public int solution(String[] maps) {
int answer = 0;
int width = maps[0].length();
int height = maps.length;
int[] start = new int[2];
for(int i = 0; i<height; i++){
for(int j = 0; j<width; j++){
if(maps[i].charAt(j) == 'S'){
start[0] = i;
start[1] = j;
break;
}
}
}
answer = bfs(maps, width, height, start, 'L');
return answer;
}
public int bfs(String[] maps, int width, int height, int[] start, char target){
boolean[][] visited = new boolean[height][width];
Queue<int[]> queue = new LinkedList<>();
queue.offer(start);
visited[start[0]][start[1]] = true;
int cnt = 0;
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i<size; i++){
int[] now = queue.poll();
if(maps[now[0]].charAt(now[1]) == target){
if(target == 'L'){
int tmp = bfs(maps, width, height, now, 'E');
if(tmp == -1) return -1;
cnt = cnt + tmp;
}
return cnt;
}
for(int j = 0; j<4; j++){ // 4방 탐색
int[] next = new int[2];
next[0] = now[0] + delta[j][0];
next[1] = now[1] + delta[j][1];
if(0<=next[0] && next[0]<height && 0<=next[1] && next[1]<width && maps[next[0]].charAt(next[1]) != 'X' && !visited[next[0]][next[1]]){
visited[next[0]][next[1]] = true;
queue.offer(next);
}
}
}
cnt++;
}
return -1;
}
}
'Algorithm > Programmers' 카테고리의 다른 글
programmers_디펜스 게임_java (0) | 2023.04.01 |
---|---|
programmers_무인도 여행_java (0) | 2023.03.30 |
programmers_광물 캐기_java (0) | 2023.03.23 |
programmers_영어 끝말잇기_java (0) | 2023.03.22 |
programmers_[1차] 셔틀버스_java (0) | 2023.03.17 |