
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
static int width, height;
static boolean[][] map;
static boolean[][][] visited;
static int[] dy = {-1, 1, 0, 0};
static int[] dx = {0, 0, -1, 1};
public static class Pos {
int y;
int x;
int dist;
int break_wall;
Pos(int y, int x, int d, int b) {
this.y = y;
this.x = x;
this.dist = d;
this.break_wall = b;
}
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
height = Integer.parseInt(st.nextToken());
width = Integer.parseInt(st.nextToken());
map = new boolean[height][width];
visited = new boolean[height][width][2];
for (int y = 0; y < height; y++) {
String line = br.readLine();
for (int x = 0; x < width; x++) {
map[y][x] = line.charAt(x) == '0';
}
}
br.close();
int result = bfs();
bw.write(result + "\n");
bw.close();
}
private static int bfs() {
Queue<Pos> queue = new LinkedList<>();
queue.add(new Pos(0, 0, 1, 0)); // y x dist wall
visited[0][0][0] = true;
while (!queue.isEmpty()) {
Pos cur = queue.poll();
if (cur.y == (height - 1) && cur.x == (width - 1)) {
return cur.dist;
}
for (int i = 0; i < 4; i++) {
int nextY = cur.y + dy[i];
int nextX = cur.x + dx[i];
if (!isValidPos(nextY, nextX)) {
continue;
}
if (!map[nextY][nextX] && cur.break_wall == 0 && !visited[nextY][nextX][1]) {
// 다음 벽인데 부순적없음
visited[nextY][nextX][1] = true;
queue.add(new Pos(nextY, nextX, cur.dist + 1, 1));
}
if (map[nextY][nextX] && !visited[nextY][nextX][cur.break_wall]) {
// 다음 이동가능한 경우 & 부수든 안부수든 방문한적 있냐없나 체크
visited[nextY][nextX][cur.break_wall] = true;
queue.add(new Pos(nextY, nextX, cur.dist + 1, cur.break_wall));
}
}
}
return -1;
}
public static boolean isValidPos(int y, int x) {
return y >= 0 && y < height && x >= 0 && x < width;
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 3015번: 오아시스 재결합 (0) | 2025.10.08 |
|---|---|
| [JAVA-자바] 2638번: 치즈 (0) | 2025.10.06 |
| [JAVA-자바] 1865번: 웜홀 (0) | 2025.05.21 |
| [JAVA-자바] 1238번: 파티 (0) | 2025.05.19 |
| [JAVA-자바] 17144번: 미세먼지 안녕! (0) | 2025.05.18 |