https://school.programmers.co.kr/learn/courses/30/lessons/169199
import java.util.*;
class Solution {
public int solution(String[] board) {
int answer = 0;
int rows = board.length;
int cols = board[0].length();
int startX = 0, startY = 0, endX = 0, endY = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i].charAt(j) == 'R') {
startX = i;
startY = j;
}
if (board[i].charAt(j) == 'G') {
endX = i;
endY = j;
}
}
}
answer = bfs(startX, startY, endX, endY, rows, cols, board);
return answer;
}
public int bfs(int sx, int sy, int ex, int ey, int rows, int cols, String[] board)
{
int[][] visited = new int[rows][cols];
int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, -1, 1};
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{sx, sy, 0});
visited[sx][sy] = 1;
while (!queue.isEmpty()) {
int[] current = queue.poll();
int x = current[0];
int y = current[1];
int count = current[2];
if (x == ex && y == ey) {
return count;
}
for (int i = 0; i < 4; i++) {
int newX = x;
int newY = y;
while (true) {
newX += dx[i];
newY += dy[i];
if(newX < 0 || newX >= rows)
break;
if(newY < 0 || newY >= cols)
break;
if(board[newX].charAt(newY) == 'D')
break;
}
newX -= dx[i];
newY -= dy[i];
if (newX == ex && newY == ey)
return count + 1;
if (visited[newX][newY] == 0 || visited[newX][newY] > count + 1)
{
visited[newX][newY] = count + 1;
queue.add(new int[]{newX, newY, count + 1});
}
}
}
return -1;
}
}