문제(출처: https://www.acmicpc.net/problem/9781)
< Knight Moves >
문제 풀이
bfs를 사용하여 문제를 해결한다.
my solution (Java)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class _9781_ { // Knight Moves
static boolean arr[][];
static int dx[] = { -1, -2, -2, -1, 1, 2, 2, 1 };
static int dy[] = { -2, -1, 1, 2, 2, 1, -1, -2 };
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
arr = new boolean[n][m];
int x1 = -1, y1 = -1, x2 = -1, y2 = -1;
for (int i = 0; i < n; i++) {
String str = bf.readLine();
for (int j = 0; j < m; j++) {
if (str.charAt(j) == '#') {
arr[i][j] = true;
} else if (str.charAt(j) == 'K') {
x1 = i;
y1 = j;
} else if (str.charAt(j) == 'X') {
x2 = i;
y2 = j;
}
}
}
System.out.println(bfs(x1, y1, x2, y2));
}
private static int bfs(int x1, int y1, int x2, int y2) {
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[] { x1, y1, 0 });
arr[x1][y1] = true;
while (!queue.isEmpty()) {
int temp[] = queue.poll();
for (int i = 0; i < 8; i++) {
int a = temp[0] + dx[i];
int b = temp[1] + dy[i];
if (a >= 0 && a < arr.length && b >= 0 && b < arr[0].length && !arr[a][b]) {
if (a == x2 && b == y2) {
return temp[2] + 1;
}
arr[a][b] = true;
queue.add(new int[] { a, b, temp[2] + 1 });
}
}
}
return -1;
}
}
변수)
n, m : 배열 크기
arr : 배열 정보
x1, x2, y1, y2 : 시작 위치, 도착 위치
배열 크기를 입력받아 배열 크기만큼 배열 정보를 입력받는다. 배열 값이 #라면 true 표시를, K라면 시작 위치를 저장하고 X라면 도착 위치를 저장한다. bfs를 호출한 반환 값을 출력한다.
bfs(시작 위치, 도착 위치)
큐에 시작 좌표를 저장한 후 큐가 빌 때까지 다음 과정을 반복한다.
1) queue poll
2) 8방향을 탐색하며 배열 범위 안이며 아직 방문하지 않은 곳이라면 방문 표시 및 queue에 추가. 이때 도착 위치와 일치한다면 temp [2]+1 반환
도착 위치에 도달할 수 없다면 -1을 반환한다.
'🌞Algorithm > 🔥Baekjoon' 카테고리의 다른 글
[Baekjoon] 30610_A-maze-ing Lakes (0) | 2024.10.17 |
---|---|
[Baekjoon] 5993_Invasion of the Milkweed (0) | 2024.10.11 |
[Baekjoon] 9700_RAINFOREST CANOPY (2) | 2024.10.08 |
[Baekjoon] 9790_Elephant Show (0) | 2024.10.07 |
[Baekjoon] 29634_Hotel (0) | 2024.10.04 |