Sangwon Coding
미로 탐색 본문
문제
N×M크기의 배열로 표현되는 미로가 있다.
1 | 0 | 1 | 1 | 1 | 1 |
1 | 0 | 1 | 0 | 1 | 0 |
1 | 0 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 0 | 1 | 1 |
미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오. 한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다.
위의 예에서는 15칸을 지나야 (N, M)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.
입력
첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
출력
첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
import java.io.*;
import java.util.*;
public class Main {
static int[] dx = { -1, 0, 1, 0 }; // 이동할 x좌표
static int[] dy = { 0, 1, 0, -1 }; // 이동할 y좌표
static int xsize;
static int ysize;
static int[][] board;
static int[][] check_board; // 방문한 좌표인지 여부
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
xsize = scan.nextInt();
ysize = scan.nextInt();
String[] str = new String[xsize];
board = new int[xsize][ysize];
check_board = new int[xsize][ysize];
for (int i = 0; i < xsize; i++) {
str[i] = scan.next();
}
for (int i = 0; i < xsize; i++) {
for (int j = 0; j < ysize; j++) {
board[i][j] = str[i].charAt(j) - '0';
check_board[i][j] = 0;
}
}
check_board[0][0] = 1;
bfs(0, 0);
System.out.println(board[xsize - 1][ysize - 1]);
}
static public void bfs(int x, int y) { // bfs 함수
Queue<Dot> q = new LinkedList<Dot>(); // Queue를 사용해야 선입선출 방식으로 잘못된 길을 찾아도 그전에 찾았던 다른 길이 시작점이되서 탐색 가능
q.add(new Dot(x, y)); // (0,0)에서 시작
while (!q.isEmpty()) {
Dot d = q.poll();
for (int i = 0; i < 4; i++) {
int next_x = d.x + dx[i]; // 다음 이동할 x좌표
int next_y = d.y + dy[i]; // 다음 이동할 y좌표
if (next_x >= xsize || next_y >= ysize || next_x < 0 || next_y < 0 || check_board[next_x][next_y] == 1
|| board[next_x][next_y] == 0) // 범위를 벗어나거나 이미 방문했거나 길이 없으면 PASS
continue;
q.add(new Dot(next_x, next_y)); // 다음 이동할 좌표를 넣음
board[next_x][next_y] = board[d.x][d.y] + 1; // 칸이 1개씩 이동하므로 +1
check_board[next_x][next_y] = 1; // 방문한 위치이므로 1로 변경
}
}
}
}
class Dot { // 좌표 클래스
int x;
int y;
Dot(int x, int y) {
this.x = x;
this.y = y;
}
}
문제출처
Comments