https://www.acmicpc.net/problem/25416
25416번: 빠른 숫자 탐색
5 x 5 크기의 보드가 주어진다. 보드는 1 x 1 크기의 정사각형 격자로 이루어져 있다. 보드의 격자에는 -1, 0, 1중 하나의 숫자가 적혀 있다. 격자의 위치는 (r, c)로 표시한다. r은 행 번호, c는 열 번호
www.acmicpc.net
저는 bfs를 통해 문제를 풀었습니다.
시작 지점부터 bfs를 통해 최단 경로로 1을 만나는 시간을 찾아 문제를 해결하였습니다.
package BOJ.bfs;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_25416 {
private static final int SIZE = 5;
private static final int BLOCK = -1;
private static final int TARGET = 1;
private static final int EMPTY = 0;
private static final int NOT_FOUND = -1;
private static final int[] DY = {-1,0,1,0};
private static final int[] DX = {0,1,0,-1};
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
Function<String,Integer> stoi = Integer::parseInt;
int[][] map = new int[SIZE][SIZE];
for(int i = 0 ; i < SIZE ; i++){
st = new StringTokenizer(br.readLine());
for(int j = 0 ; j < SIZE ; j++){
map[i][j] = stoi.apply(st.nextToken());
}
}
st = new StringTokenizer(br.readLine());
int startY = stoi.apply(st.nextToken());
int startX = stoi.apply(st.nextToken());
int result = bfs(startY,startX,map);
System.out.println(result);
}
private static int bfs(int startY, int startX, int[][] map) {
Queue<int[]> q = new LinkedList<>();
q.offer(new int[]{startY,startX});
int time = 0;
boolean[][] visited = new boolean[SIZE][SIZE];
visited[startY][startX] = true;
while(!q.isEmpty()){
int size = q.size();
for(int s = 0 ; s < size ; s++){
int[] now = q.poll();
if(map[now[0]][now[1]] == TARGET){
return time;
}
for(int i = 0 ; i < 4; i++){
int ny = now[0] + DY[i];
int nx = now[1] + DX[i];
if(ny >= 0 && ny < SIZE && nx >= 0 && nx < SIZE && !visited[ny][nx] && map[ny][nx] != BLOCK){
visited[ny][nx] = true;
q.offer(new int[]{ny,nx});
}
}
}
time++;
}
return NOT_FOUND;
}
}
'알고리즘' 카테고리의 다른 글
백준 10810번 공 넣기 (JAVA) (0) | 2023.09.11 |
---|---|
백준 14627번 파닭파닭(JAVA) (0) | 2023.09.10 |
백준 5546번 파스타 (JAVA) (0) | 2023.09.08 |
백준 2637번 장난감 조립 (JAVA) (0) | 2023.09.07 |
백준 15658번 연산자 끼워넣기2 (JAVA) (0) | 2023.09.06 |