BFS를 이용한 문제 였습니다.
Node 클래스를 만들어 x,y의 값을 저장하여 사용하며,
dx,dy 배열를 이용하여 위치를 상,하,좌,우 이동하면서 탐색 할 수 있게 하였습니다.
import java.util.*;
class Node{
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
public class 미로탈출 {
static int N,M;
static int[][] grph = new int[201][201];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
sc.nextLine(); //Remove buffer
for(int i=1; i<=N;i++) {
String str = sc.nextLine();
for(int j=1; j<=M;j++) {
grph[i][j]= str.charAt(j-1)-'0';
}
}
System.out.println(bfs(1,1));
}
public static int bfs(int x, int y) {
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
Queue<Node> queue = new LinkedList<>();
queue.offer(new Node(x,y));
while(!queue.isEmpty()) {
Node node = queue.poll();
x = node.getX();
y = node.getY();
for(int i=0 ; i<4;i++) {
int nx = x+dx[i];
int ny = y+dy[i];
if(nx<1 || nx>N || ny<1 || ny>M) continue;
if(grph[nx][ny]==0)continue;
if(grph[nx][ny]==1) {
grph[nx][ny] = grph[x][y]+1;
queue.offer(new Node(nx,ny));
}
}
}
return grph[N][M];
}
}
https://www.acmicpc.net/problem/2178
아직 BFS와 DFS를 사용하여 문제를 풀이하는데
익숙하지 않아,
복습과 여러문제를 풀어서
익숙해 져야할거 같습니다.
'알고리즘' 카테고리의 다른 글
[백준] 4963 : 섬의개수 - JAVA (0) | 2021.12.07 |
---|---|
[프로그래머스] 로또의 최고 순위와 최저 순위 - JAVA (0) | 2021.11.01 |