https://www.acmicpc.net/problem/14497
저는 bfs와 우선순위 큐를 통해 문제를 해결하였습니다.
bfs로 모든 경로를 탐색하여 목표까지 최단거리를 찾았습니다.
처음에는 큐를 통해 문제를 해결하여 하였지만, 이럴 경우 메모리 초과가 나오게 되어 우선순위 큐를 통해 현재 가장 가까운 지점부터 진행하도록 하여 해결하였습니다.
package BOJ.bfs;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
public class BOJ_14497 {
private static final char EMPTY = '0';
private static final char FRIEND = '1';
private static final char TARGET = '#';
private static final char START = '*';
private static final int NOT_VALID = -1;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
int startY = Integer.parseInt(st.nextToken())-1;
int startX = Integer.parseInt(st.nextToken())-1;
int endY = Integer.parseInt(st.nextToken())-1;
int endX = Integer.parseInt(st.nextToken())-1;
char[][] map = new char[n][m];
for (int i = 0; i < n; i++) {
String command = br.readLine();
for (int j = 0; j < m; j++) {
map[i][j] = command.charAt(j);
}
}
int result = bfs(startY, startX, endY, endX, map, n, m);
System.out.println(result);
}
private static final int[] DY = {-1, 0, 1, 0};
private static final int[] DX = {0, 1, 0, -1};
private static int bfs(int startY, int startX, int endY, int endX, char[][] map, int n, int m) {
PriorityQueue<int[]> q = new PriorityQueue<>((v1,v2)->{
return v1[2] - v2[2];
});
q.offer(new int[]{startY, startX, 0});
int[][] visited = new int[n][m];
for(int i = 0 ; i < n ; i++){
Arrays.fill(visited[i],NOT_VALID);
}
while (!q.isEmpty()) {
int[] now = q.poll();
for (int i = 0; i < 4; i++) {
int ny = now[0] + DY[i];
int nx = now[1] + DX[i];
int cnt = now[2];
if (ny >= 0 && ny < n && nx >= 0 && nx < m) {
if (map[ny][nx] != EMPTY) {
cnt++;
}
if((visited[ny][nx] != 0 && visited[ny][nx] > cnt) || visited[ny][nx] == NOT_VALID){
visited[ny][nx] = cnt;
q.offer(new int[]{ny,nx,cnt});
}
}
}
}
return visited[endY][endX];
}
}
'알고리즘' 카테고리의 다른 글
백준 2852번 NBA농구 (JAVA) (0) | 2023.10.12 |
---|---|
백준 14495번 피보나치 비스무리한 수열 (JAVA) (1) | 2023.10.11 |
백준 29703번 펭귄의 하루 (JAVA) (1) | 2023.10.09 |
백준 1251번 단어 나누기 (JAVA) (0) | 2023.10.08 |
백준 14607번 피자 (JAVA) (1) | 2023.10.07 |