반응형
https://www.acmicpc.net/problem/14442
문제 해결 알고리즘
벽 부수고 이동하기 1에서 했던 걸 갯수만 늘려주는 식으로 배열도 늘려주고 벽 부술 수 있는 개수도 늘려준다.
https://kimmessi.tistory.com/134
소스 코드
#include <bits/stdc++.h>
#define MAX 1001
using namespace std;
int graph[MAX][MAX];
int visited[MAX][MAX][11];
int N, M, K;
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
typedef struct pos {
int x;
int y;
int block;
}pos;
bool isIn(int x, int y){
return 0<=x && x<N && 0<=y && y<M;
}
int bfs(){
queue<pos> q;
q.push({0, 0, K});
visited[0][0][K] = 1;
while(!q.empty()){
int cur_x = q.front().x;
int cur_y = q.front().y;
int cur_block = q.front().block;
q.pop();
for(int i=0;i<4;i++){
int next_x = cur_x + dir[i][0];
int next_y = cur_y + dir[i][1];
if(next_x == N-1 && next_y == M-1) return visited[cur_x][cur_y][cur_block] + 1;
if(isIn(next_x, next_y)){
if(graph[next_x][next_y] == 1 && cur_block > 0 && visited[next_x][next_y][cur_block-1] == 0){
visited[next_x][next_y][cur_block-1] = visited[cur_x][cur_y][cur_block] + 1;
q.push({next_x, next_y, cur_block-1});
}
else if(graph[next_x][next_y] == 0 && visited[next_x][next_y][cur_block] == 0){
visited[next_x][next_y][cur_block] = visited[cur_x][cur_y][cur_block] + 1;
q.push({next_x, next_y, cur_block});
}
}
}
}
return 0;
}
int main(){
cin >> N >> M >> K;
if(N == 1 && M == 1){
cout << 1;
return 0;
}
for(int i=0;i<N;i++){
string str; cin >> str;
for(int j=0;j<M;j++){
graph[i][j] = str[j] - '0';
}
}
int result = bfs();
if(!result) cout << -1;
else cout << result;
}
반응형
'알고리즘 문제 해결 > BOJ' 카테고리의 다른 글
[자료구조, 우선순위 큐] BOJ 14698 전생했더니 슬라임 연구자였던 건에 대하여(Hard) (0) | 2022.02.05 |
---|---|
[자료구조, 우선순위 큐] BOJ 2075 N번째 큰 수 (0) | 2022.02.02 |
[BFS] BOJ 2206 벽 부수고 이동하기 (0) | 2022.01.27 |
[BFS] BOJ 6593 상범 빌딩 (0) | 2022.01.24 |
[BFS] BOJ 2589 보물섬 (0) | 2022.01.21 |