[프로그래머스] 리코쳇 로봇 (Java)
https://school.programmers.co.kr/learn/courses/30/lessons/169199
입력 : 게임판의 상태를 나타내는 문자열 배열 board
출력 : 말이 목표위치에 도달하는데 이동해야하는 최소 거리. 단, 목표 위치에 도달할 수 없다면 -1 리턴
O(n)
bfs
구현
import java.util.*;
class Solution {
private int[] dx = {0, 0, -1, 1}; // Direction vectors for row movement
private int[] dy = {-1, 1, 0, 0}; // Direction vectors for column movement
static class Point {
int x, y, depth;
Point(int x, int y, int depth) {
this.x = x;
this.y = y;
this.depth = depth;
}
}
public int solution(String[] board) {
int n = board.length;
int m = board[0].length();
boolean[][] visited = new boolean[n][m];
Queue<Point> queue = new LinkedList<>();
Point start = null, goal = null;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i].charAt(j) == 'R') {
start = new Point(i, j, 0);
}
if (board[i].charAt(j) == 'G') {
goal = new Point(i, j, 0);
}
}
}
queue.add(start);
visited[start.x][start.y] = true;
while (!queue.isEmpty()) {
Point current = queue.poll();
if (current.x == goal.x && current.y == goal.y) {
return current.depth;
}
for (int i = 0; i < 4; i++) {
int nx = current.x;
int ny = current.y;
while (nx + dx[i] >= 0 && nx + dx[i] < n && ny + dy[i] >= 0 && ny + dy[i] < m
&& board[nx + dx[i]].charAt(ny + dy[i]) != 'D') {
nx += dx[i];
ny += dy[i];
}
if (!visited[nx][ny]) {
visited[nx][ny] = true;
queue.add(new Point(nx, ny, current.depth + 1));
}
}
}
return -1;
}
}