반응형
https://www.acmicpc.net/problem/1261
문제 해결 알고리즘
0-1 BFS 문제
정점이 0이면 덱 앞에 1이면 덱 뒤에 놓는 BFS 문제이다.
소스 코드
#include <bits/stdc++.h>
using namespace std;
int M, N;
int arr[101][101], cnt[101][101];
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
bool isIn(int x, int y){
return 0<x && x<=N && 0<y && y<=M;
}
void bfs(){
deque<pair<int, pair<int, int>>> dq;
dq.push_back({0, {1, 1}});
cnt[1][1] = 0;
while(!dq.empty()){
int cur_num = dq.front().first;
int cur_x = dq.front().second.first;
int cur_y = dq.front().second.second;
if(cur_x == N && cur_y == M){
cout << cur_num;
return;
}
dq.pop_front();
for(int i=0;i<4;i++){
int next_x = cur_x + dir[i][0];
int next_y = cur_y + dir[i][1];
if(isIn(next_x, next_y) && cnt[cur_x][cur_y] + arr[next_x][next_y] < cnt[next_x][next_y]){
if(arr[next_x][next_y]) dq.push_back({cur_num + 1,{next_x, next_y}});
else dq.push_front({cur_num ,{next_x, next_y}});
cnt[next_x][next_y] = cnt[cur_x][cur_y] + arr[next_x][next_y];
}
}
}
}
int main(){
cin >> M >> N;
for(int i=1;i<=N;i++){
string str; cin >> str;
for(int j=0;j<M;j++){
arr[i][j+1] = str[j] - '0';
cnt[i][j+1] = INT_MAX;
}
}
bfs();
}
반응형
'알고리즘 문제 해결 > BOJ' 카테고리의 다른 글
[DP] BOJ 13398 연속합 2 (C++) (0) | 2022.10.23 |
---|---|
[그리디] BOJ 12931 두 배 더하기 (C++) (0) | 2022.10.20 |
[0-1 BFS] BOJ 13549 숨바꼭질 3 (C++) (0) | 2022.10.14 |
[우선순위 큐] BOJ 7662 이중 우선순위 큐 (C++) (0) | 2022.10.11 |
[백트래킹] BOJ 1062 가르침 (C++) (0) | 2022.10.08 |