백준 14442 벽 부수고 이동하기2
문제
https://www.acmicpc.net/problem/14442
접근방법
3차원 BFS
풀이코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int N, M, K, ans=-1;
static char[][] map;
static int[] dr = {-1,0,1,0};
static int[] dc = {0,1,0,-1};
private static class Pos {
int r,c,k,move;
public Pos(int r, int c, int k, int move) {
super();
this.r = r;
this.c = c;
this.k = k;
this.move = move;
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
// 1. 입력 및 초기화
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine(), " ");
N = Integer.parseInt(st.nextToken()); // 행
M = Integer.parseInt(st.nextToken()); // 열
K = Integer.parseInt(st.nextToken()); // 벽 부술 수 있는 갯수
map = new char[N][M];
for(int i=0; i<N; i++) map[i] = in.readLine().toCharArray();
// 2. bfs
bfs(0, 0);
// 3. 정답 출력
System.out.println(ans);
}
public static void bfs(int sr, int sc) {
Queue<Pos> que = new LinkedList<Pos>();
boolean[][][] visited = new boolean[K+1][N][M];
que.offer(new Pos(sr, sc, 0, 1));
visited[0][sr][sc] = true;
while(!que.isEmpty()) {
Pos p = que.poll();
int r = p.r;
int c = p.c;
int k = p.k;
int move = p.move;
if(r == N-1 && c == M-1) {
ans = move;
break;
} // 탈출 성공
int nr, nc;
for(int d=0; d<4; d++) {
nr = r + dr[d];
nc = c + dc[d];
if(nr > -1 && nr < N && nc > -1 && nc < M) {
// 1) 길인 경우
if(!visited[k][nr][nc] && map[nr][nc] == '0') {
visited[k][nr][nc] = true;
que.offer(new Pos(nr, nc, k, move+1));
}
// 2) 벽인 경우
else if(k+1 <= K && !visited[k+1][nr][nc] && map[nr][nc] == '1') {
visited[k+1][nr][nc] = true;
que.offer(new Pos(nr, nc, k+1, move+1));
}
}
}
}
}
}