CS/Algorithm
[백준:2178] 미로탐색 - JAVA
yujindonut
2021. 5. 2. 19:51
728x90
import java.util.*;
class Location{
int x, y;
public Location(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Main {
static int map[][]; // 2차원 미로 배열
static int isVisit[][]; // 2차원 방문여부 배열
static int n,m;
static int[] xArr = {-1,0,1,0};
static int[] yArr = {0,1,0,-1};
public static void bfs() { //BFS메소드
Queue<Location> q = new LinkedList<>();
q.add(new Location(1,1)); //큐에 시작점들을 추가
isVisit[1][1] = 1;
while(!q.isEmpty()) {
Location location = q.poll();
int qx = location.x;
int qy = location.y;
//상하좌우 4방향 노드 범위 벗어나는지 탐색
for(int i = 0; i < 4; i++) {
int x = qx + xArr[i];
int y = qy + yArr[i];
if(checkLocation(x,y)) {
//큐에 인접한 노드 추가
q.add(new Location(x,y));
//추가한 노드까지의 거리 = 현재 노드 까지의 거리 + 1
isVisit[x][y] = isVisit[qx][qy] + 1;
}
}
}
System.out.println(isVisit[n][m]);
}
public static boolean checkLocation(int x, int y) {
//범위 벗어나면
if(x < 1 || x > n || y < 1 || y > m) return false;
//이미 방문한 노드거나 간선이 없는 경우
if(isVisit[x][y] != 0 || map[x][y] == 0) return false;
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
map = new int [n + 1][m + 1];
isVisit = new int[n + 1][m + 1];
for(int i = 1; i <= n; i++) { // 줄단위로 입력이 이루어질 때 값을 저장하는 방식
String row = sc.next();
for(int j = 1; j <= m; j++) {
map[i][j] = row.charAt(j - 1) - '0';
}
}
bfs(); // 시작점 전달
sc.close();
}
}
728x90