[ 문제 ]
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개의 정수로 미로가 주어진다.
- 각각의 수들은 붙어서 입력으로 주어진다.
[ 출력 ]
- 첫째 줄에 지나야 하는 최소의 칸 수를 출력한다.
- 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
[ 예제 입력 ]
4 6
101111
101010
101011
111011
[ 예제 출력 ]
15
import java.util.*;
import java.io.*;
public class Main {
static class Node {
int row, column;
Node (int row, int column){
this.row = row;
this.column = column;
}
}
static int N, M;
static char[][] map;
static boolean[][] visited;
static int[] dr = {0, 0, -1, 1};
static int[] dc = {-1, 1, 0, 0};
private static void bfs (int i, int j) {
Queue<Node> queue = new LinkedList<>();
queue.offer(new Node(i, j));
while (!queue.isEmpty()) {
Node current = queue.poll();
visited[current.row][current.column] = true;
for (int d = 0; d < 4; d++) {
if (current.row+dr[d] >= 0 && current.row+dr[d] < N && current.column+dc[d] >= 0 && current.column+dc[d] < M
&& map[current.row+dr[d]][current.column+dc[d]] != '0' && !visited[current.row+dr[d]][current.column+dc[d]]) {
queue.offer(new Node(current.row+dr[d], current.column+dc[d]));
visited[current.row+dr[d]][current.column+dc[d]] = true;
map[current.row+dr[d]][current.column+dc[d]] += map[current.row][current.column]-'0';
if (current.row+dr[d] == N-1 && current.column+dc[d] == M-1)
return;
}
}
}
}
public static void main (String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken()); // 행
M = Integer.parseInt(st.nextToken()); // 열
map = new char[N][M];
for (int i = 0; i < N; i++)
map[i] = br.readLine().toCharArray();
visited = new boolean[N][M];
bfs(0, 0);
System.out.println(map[N-1][M-1] - '0');
}
}
'Algorithm > 백준+프로그래머스+SWEA+정올+구름' 카테고리의 다른 글
[Algorithm] 백준 17178 줄서기 (0) | 2022.04.25 |
---|---|
[Algorithm] 백준 7576 토마토 (0) | 2021.09.12 |
[Algorithm] 백준 2606 바이러스 (0) | 2021.09.12 |
[Algorithm] 백준 4963 섬의 개수 (0) | 2021.09.11 |
[Algorithm] 백준 2667 단지번호붙이기 (0) | 2021.09.11 |