programmers_리코쳇 로봇_java
2023. 5. 21. 19:07ㆍAlgorithm/Programmers
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/169199
import java.util.*;
class Solution {
private static int[][] delta = {{0,1} , {1, 0}, {0, -1}, {-1, 0}};
public int solution(String[] board) {
int answer = 0;
// start 찾기
int y = 0;
for (String s : board){
boolean res = false;
for (int i = 0; i< s.length(); i++){
if (s.charAt(i) == 'R'){
answer = bfs(board, new int[]{y, i});
res = true;
break;
}
}
if (res) break;
y++;
}
return answer;
}
//bfs 탐색
public int bfs(String[] board, int[] start){
Queue<int[]> queue = new LinkedList<>();
queue.offer(start);
int width = board[0].length();
int height = board.length;
boolean[][] visited = new boolean[height][width];
int cnt = 0;
while (!queue.isEmpty()){
int size = queue.size();
for (int i = 0; i<size; i++){
int[] now = queue.poll();
if (visited[now[0]][now[1]]) continue;
visited[now[0]][now[1]] = true;
if (board[now[0]].charAt(now[1]) == 'G'){
return cnt;
}
for (int j = 0; j<4; j++){
queue.offer(move(now, j, width, height, board));
}
}
cnt++;
}
return -1;
}
//dir 방향으로 계속 이동
public int[] move(int[] start, int dir, int width, int height, String[] board){
int[] now = new int[2];
now[0] = start[0];
now[1] = start[1];
while (true){
int nexty = now[0] + delta[dir][0];
int nextx = now[1] + delta[dir][1];
if (0<=nexty && nexty < height
&& 0<= nextx && nextx < width
&& board[nexty].charAt(nextx) != 'D'
){
now[0] = nexty;
now[1] = nextx;
}else {
return now;
}
}
}
}
'Algorithm > Programmers' 카테고리의 다른 글
programmers_숫자 블록_java (0) | 2023.05.22 |
---|---|
programmers_두 원 사이의 정수 쌍_java (0) | 2023.05.21 |
programmers_우박수열 정적분_java (1) | 2023.05.21 |
programmers_N-Queen_java (0) | 2023.05.19 |
programmers_시소 짝꿍_java (0) | 2023.05.18 |