조앤의 기술블로그
[백준 / BFS] #2178 미로탐색(java) 본문
문제
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 문제.
큐에 저장할 때 좌표값과 지나온 칸의 개수(count)를 같이 저장하다가 목적지에 도착했을 때 출력해주면 된다.
자바에서는 여러 개의 값을 큐에 저장할 때 클래스를 만들었다.
[코드]
import java.util.*;
import java.io.*;
public class Main {
static private class Node {
int x;
int y;
int count; //지난 칸의 개수
public Node(int x, int y, int count) {
this.x = x;
this.y = y;
this.count = count;
}
}
static int stoi(String s) {
return Integer.parseInt(s);
}
static int[][] arr;
static int[] dx = {1, -1, 0, 0};
static int[] dy = {0, 0, 1, -1};
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
int N = stoi(st.nextToken());
int M = stoi(st.nextToken());
arr = new int[N][M];
for(int i=0; i<N; i++) {
String s = br.readLine();
for(int j=0; j<M; j++) {
arr[i][j] = s.charAt(j) - '0';
}
}
bfs(N, M);
}
static void bfs(int n, int m) {
int[][] visited = new int[n][m];
Queue<Node> queue = new LinkedList<Node>();
Node start = new Node(0, 0, 1);
queue.add(start);
while(!queue.isEmpty()) {
Node now = queue.poll();
// arrival
if(now.x == n-1 && now.y == m-1) {
//return now.count;
System.out.println(now.count);
}
for(int i=0; i<4; i++) {
int nx = now.x + dx[i];
int ny = now.y + dy[i];
int count = now.count;
if(0 <= nx && nx < n && 0<= ny && ny <m) {
if(arr[nx][ny] == 1 && visited[nx][ny] != 1) {
Node node = new Node(nx, ny, count+1);
queue.add(node);
visited[nx][ny] = 1;
}
}
}
}
}
}
[참고]
뱀귤님 블로그
https://bcp0109.tistory.com/86?category=847904
[출처]
https://www.acmicpc.net/problem/2178
'Programming > 백준' 카테고리의 다른 글
[백준 / DFS] (틀림)#11724 연결 요소의 개수 (java) (0) | 2020.03.13 |
---|---|
[백준 / BFS] (틀림)#7576 토마토 (java) (0) | 2020.03.12 |
[백준 / DFS] #2667 단지번호 붙이기(java) (0) | 2020.03.11 |
[백준 / BFS] #16940 BFS 스페셜 저지 (java) (0) | 2020.03.11 |
[백준 / DP] #14501 퇴사 (python, java) (0) | 2020.03.11 |