https://www.acmicpc.net/problem/2178
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개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
이동할 최소한의 거리 즉, 최단거리를 구해야 하기 때문에 BFS로 바로 접근했다. BFS를 이용해서 풀이는 어려운 문제는 아니나, 아직 객체지향적으로 작성하는데 어색하다.
package 완전탐색;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Location{
int row,col;
public Location(int row,int col) {
this.row=row;
this.col=col;
}
}
public class 백준_2178_S1_미로탐색 {
static int N,M;
static int map[][];
static int isVisit[][];
static int dx[]= {-1,0,1,0};
static int dy[]= {0,1,0,-1};
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine()," ");
N=Integer.parseInt(st.nextToken());
M=Integer.parseInt(st.nextToken());
map=new int[N+1][M+1];
isVisit=new int[N+1][M+1];
for(int i=1;i<=N;i++) {
String str = br.readLine();
for(int j=1;j<=M;j++) {
map[i][j]=str.charAt(j-1)-'0';
}
}
bfs();
bw.write(sb.toString());
br.close();
bw.close();
}
public static void bfs() {
Queue<Location> queue = new LinkedList<>();
//큐에 시작점
queue.add(new Location(1,1));
isVisit[1][1]=1; // 방문처리
while(!queue.isEmpty()) {
Location location = queue.poll();
int row=location.row;
int col = location.col;
for(int i=0;i<4;i++) {
int x= row+dx[i];
int y= col+dy[i];
if(check(x, y)) {
queue.add(new Location(x,y));
isVisit[x][y]=isVisit[row][col]+1; //추가한 노드에 이전까지 간 거리+1;
}
}
}
sb.append(isVisit[N][M]);
}
public static boolean check(int row,int col) {
if(row<1 || row>N || col<1 || col>M)
return false;
if(isVisit[row][col]!=0 || map[row][col]==0) // 이미 방문한 경우 또는 못가는 경우
return false;
return true;
}
}