5427번: 불
상근이는 빈 공간과 벽으로 이루어진 건물에 갇혀있다. 건물의 일부에는 불이 났고, 상근이는 출구를 향해 뛰고 있다. 매 초마다, 불은 동서남북 방향으로 인접한 빈 공간으로 퍼져나간다. 벽에
www.acmicpc.net
- 풀이
문제는 어렵기보단 입력값이 크지 않기때문에 문제에 조건대로 구현만 잘하면되는 문제입니다.
문제의 조건은 다음과 같습니다.
- '.': 빈 공간
- '#': 벽
- '@': 상근이의 시작 위치
- '*': 불
의 입력에서 @인 상근이를 벽과 불을 피해서 배열 밖으로 빼낼 수 있으면 최소값 출력, 빼낼 수 없다면 IMPOSSIZBLE을 출력하면 되는 문제입니다. 단, *인 불과 @인 상근이는 1초마다 상,하,좌,우로 1칸씩 움직일 수 있습니다. 또한 불이 불이 먼저 번지기 때문에 상근이는 현재 불이 상, 하, 좌, 우로 퍼진 위치로 갈 수 없고 불은 현재 상근이가 위치한 좌표로 번질 수 있지만 상근이는 움직일 수 있다면 상관없습니다. 여기까지가 문제에 대한 조건들 입니다.
풀이 방법은 bfs를 사용했고, queue에 현재 저장되어있는 불들을 다 번지게 한 뒤, 상근이를 움직일 수 있게 해주었습니다. 만약, 상근이가 범위 밖으로 갈 수 있을 시 움직인 횟수를 return해주었고 상근이가 더이상 움직일 수 없어서 반복문이 종료되게 될때까지 return하지 못했다면 상근이는 건물을 벗어날 수 없는 것이기 때문에 -1을 return 해주었습니다.
- 코드
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
public class Main {
static int w, h;
static StringBuilder sb;
static char[][] array;
static boolean[][] check;
static Queue<Sang> sang;
static Queue<Node> fire;
static int[] dx = { 0, 0, -1, 1 };
static int[] dy = { -1, 1, 0, 0 };
public static void main(String[] args) throws Exception {
SetData();
System.out.println(sb);
}
// 데이터
private static void SetData() throws Exception {
InputReader in = new InputReader(System.in);
sb = new StringBuilder();
int testcase = in.nextInt();
for (int i = 0; i < testcase; i++) {
w = in.nextInt();
h = in.nextInt();
array = new char[h][w];
check = new boolean[h][w];
sang = new LinkedList<>();
fire = new LinkedList<>();
for (int a = 0; a < h; a++) {
String s = in.nextLine();
for (int b = 0; b < w; b++) {
array[a][b] = s.charAt(b);
if (array[a][b] == '*')
fire.add(new Node(a, b));
if (array[a][b] == '@')
sang.add(new Sang(a, b, 0));
}
}
int answer = bfs();
if (answer == -1) {
sb.append("IMPOSSIBLE").append("\n");
} else {
sb.append(answer).append("\n");
}
}
}
private static int bfs() {
while (!sang.isEmpty()) {
// 불 1초 이동
int fireSize = fire.size();
for (int i = 0; i < fireSize; i++) {
Node node = fire.poll();
for (int direction = 0; direction < 4; direction++) {
int r = node.x + dx[direction];
int c = node.y + dy[direction];
if (r < 0 || c < 0 || r >= h || c >= w)
continue;
if (array[r][c] == '#' || array[r][c] == '*')
continue;
array[r][c] = '*';
fire.add(new Node(r, c));
}
}
// 상근이 1초 이동
int sangSize = sang.size();
for (int i = 0; i < sangSize; i++) {
Sang temp = sang.poll();
check[temp.x][temp.y] = true;
for (int direction = 0; direction < 4; direction++) {
int r = temp.x + dx[direction];
int c = temp.y + dy[direction];
if (r < 0 || c < 0 || r >= h || c >= w)
return temp.count + 1;
if (array[r][c] != '.' || check[r][c])
continue;
check[r][c] = true;
sang.add(new Sang(r, c, temp.count + 1));
}
}
}
return -1;
}
}
class Node {
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
class Sang {
int x;
int y;
int count;
public Sang(int x, int y, int count) {
this.x = x;
this.y = y;
this.count = count;
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
'algorithm' 카테고리의 다른 글
[BOJ/JAVA] 백준 4485번 : 녹색 옷 입은 애가 젤다지? (0) | 2021.10.28 |
---|---|
[BOJ/JAVA] 백준 1238번 : 파티 (0) | 2021.10.27 |
[프로그래머스/JAVA] 위클리 챌린지 12주차(피로도) (0) | 2021.10.25 |
[BOJ/JAVA] 백준 1167번 : 트리의 지름 (0) | 2021.10.25 |
[BOJ/JAVA] 백준 1939번 : 중량제한 (0) | 2021.10.23 |