on
[백준] 1261번 - 알고스팟 (java)
[백준] 1261번 - 알고스팟 (java)
문제
알고스팟 운영진이 모두 미로에 갇혔다. 미로는 NM 크기이며, 총 11크기의 방으로 이루어져 있다. 미로는 빈 방 또는 벽으로 이루어져 있고, 빈 방은 자유롭게 다닐 수 있지만, 벽은 부수지 않으면 이동할 수 없다. 알고스팟 운영진은 여러명이지만, 항상 모두 같은 방에 있어야 한다. 즉, 여러 명이 다른 방에 있을 수는 없다. 어떤 방에서 이동할 수 있는 방은 상하좌우로 인접한 빈 방이다. 즉, 현재 운영진이 (x, y)에 있을 때, 이동할 수 있는 방은 (x+1, y), (x, y+1), (x-1, y), (x, y-1) 이다. 단, 미로의 밖으로 이동 할 수는 없다. 벽은 평소에는 이동할 수 없지만, 알고스팟의 무기 AOJ를 이용해 벽을 부수어 버릴 수 있다. 벽을 부수면, 빈 방과 동일한 방으로 변한다. 만약 이 문제가 알고스팟에 있다면, 운영진들은 궁극의 무기 sudo를 이용해 벽을 한 번에 다 없애버릴 수 있지만, 안타깝게도 이 문제는 Baekjoon Online Judge에 수록되어 있기 때문에, sudo를 사용할 수 없다. 현재 (1, 1)에 있는 알고스팟 운영진이 (N, M)으로 이동하려면 벽을 최소 몇 개 부수어야 하는지 구하는 프로그램을 작성하시오.
시간 제한 메모리 제한 제출 정답 맞힌 사람 정답 비율 1 초 (추가 시간 없음) 128 MB 25751 10716 7153 41.135%
입력
첫째 줄에 미로의 크기를 나타내는 가로 크기 M, 세로 크기 N (1 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 미로의 상태를 나타내는 숫자 0과 1이 주어진다. 0은 빈 방을 의미하고, 1은 벽을 의미한다. (1, 1)과 (N, M)은 항상 뚫려있다.
출력
첫째 줄에 알고스팟 운영진이 (N, M)으로 이동하기 위해 벽을 최소 몇 개 부수어야 하는지 출력한다.
풀이
PriorityQueue를 이용해 쉽게 풀 수 있다.(다익스트라)
너비우선탐색으로 빈 공간일 때는 count + 0으로, 벽일 경우에는 count +1로 queue에 넣는다. count가 적은것을 먼저 꺼내 탐색을 진행한다.
위 방식으로 진행하면 일단 이동할 수 있는 곳을 모두 먼저 탐색한 후 벽을 부수고 탐색하게 된다.
최종 소스코드
import java.io.*; import java.util.*; public class BJ_G4_1261_알고스팟 { static int N, M; static int[][] map; static int answer = 9999; static int[][] deltas = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; static StringTokenizer st; static class RC implements Comparable{ int r, c; int cnt; public RC(int r, int c, int cnt) { super(); this.r = r; this.c = c; this.cnt = cnt; } @Override public int compareTo(RC o) { return this.cnt - o.cnt; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); st = new StringTokenizer(br.readLine()); M = Integer.parseInt(st.nextToken()); N = Integer.parseInt(st.nextToken()); map = new int[N][M]; for (int i = 0; i < N; i++) { String str = br.readLine(); for (int j = 0; j < M; j++) { map[i][j] = str.charAt(j) - '0'; } } bfs(); System.out.println(answer); } static void bfs() { PriorityQueue queue = new PriorityQueue<>(); queue.offer(new RC(0, 0, 0)); boolean[][] visited = new boolean[N][M]; visited[0][0] = true; while (!queue.isEmpty()) { RC temp = queue.poll(); if (temp.r == N - 1 && temp.c == M - 1) { answer = Math.min(temp.cnt, answer); return; } for (int i = 0; i < 4; i++) { int nr = temp.r + deltas[i][0]; int nc = temp.c + deltas[i][1]; if (isIn(nr, nc) && !visited[nr][nc]) { if (map[nr][nc] == 0) { queue.offer(new RC(nr, nc, temp.cnt)); } if(map[nr][nc] == 1){ queue.offer(new RC(nr, nc, temp.cnt + 1)); } visited[nr][nc] = true; } } } } static boolean isIn(int r, int c) { return r >= 0 && r < N && c >= 0 && c < M; } }
from http://skdltm117.tistory.com/46 by ccl(A) rewrite - 2021-12-15 19:27:44