2178
문제
2178
접근
- 전형적인 그래프 탐색 문제이다.
- 시작 지점은 무조건 1,1의 위치일 것이다.
- 그래프 탐색하여 가장 짧은 거리를 반환하면 될 것같다.
- 해당 그래프 탐색을 위해 DFS로 이용한다.
- 칸 수는 100 이하로 DFS로 풀이가 가능 할 것 같다.
- DFS로는 최단 길이를 보장할 수 없다고 한다..
가정
- 보드 판을 세팅한다.
- 해당 보드 판이 1인 경우에만 다음 위치로 이동한다.
- BFS가 최단 경로를 보장한다.
풀어보기
package org.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
static int N;
static int M;
static int[][] board;
static boolean[][] visited;
private static final int[] dx = {-1, 1, 0, 0};
private static final int[] dy = {0, 0, -1, 1};
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] first = reader.readLine().split(" ");
N = Integer.parseInt(first[0]);
M = Integer.parseInt(first[1]);
board = new int[N][M];
visited = new boolean[N][M];
for(int i = 0; i < N; i++){
String [] col = reader.readLine().split("");
for(int j = 0; j < M; j++){
board[i][j] = Integer.parseInt(col[j]);
}
}
BFS(0,0);
System.out.println(board[N-1][M-1]);
}
public static void BFS(int row, int col){
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{row, col});
visited[row][col] = true;
while(!queue.isEmpty()){
int[] cur = queue.poll();
int x = cur[0];
int y = cur[1];
for(int i = 0; i < 4; i++){
int nextRow = x + dx[i];
int nextCol = y + dy[i];
if(nextCol < 0) continue;
if(nextRow < 0) continue;
if(nextRow >= N) continue;
if(nextCol >= M) continue;
if(visited[nextRow][nextCol]) continue;
if(board[nextRow][nextCol] == 0)continue;
board[nextRow][nextCol] = board[x][y] + 1;
visited[nextRow][nextCol] = true;
queue.offer(new int[]{nextRow, nextCol});
}
}
}
}
시행착오
- BFS는 어떻게 최단 경로를 보장할까?
- 가장 가까운 순서부터 탐색 == 가장 낮은 depth부터 탐색
- Queue는 FIFO로 처리 == 가장 빨리 들어온 노드부터 처리
참고자료