cgy12306
[백준 BoJ] 2206 - 벽 부수고 이동하기 본문
// https://www.acmicpc.net/problem/2206
// 벽 부수고 이동하기
#include<iostream>
#include<string>
#include<queue>
using namespace std;
int N, M;
int map[1002][1002];
int visited[1002][1002][2];
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,1,-1 };
queue<pair<pair<int, int>, int>> q;
int bfs() {
visited[1][1][1] = 1;
q.push({{ 1,1 }, 1});
while (!q.empty()) {
int x = q.front().first.first;
int y = q.front().first.second;
int b = q.front().second;
q.pop();
if (x == N && y == M) return visited[x][y][b];
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx <= 0 || ny <= 0 || nx > N || ny > M) continue;
if (map[nx][ny] == 1 && b == 1) {
visited[nx][ny][b - 1] = visited[x][y][b] + 1;
q.push({ {nx, ny}, b - 1 });
}
else if (map[nx][ny]==0 && visited[nx][ny][b]==0) {
visited[nx][ny][b] = visited[x][y][b] + 1;
q.push({ {nx,ny}, b });
}
}
}
return -1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> N >> M;
for (int i = 1; i <= N; i++) {
string s;
cin >> s;
for (int j = 1; j <= s.size(); j++) {
map[i][j] = s[j-1] - '0';
}
}
int ans = bfs();
cout << ans;
}
- BFS
'Algorithm > C++' 카테고리의 다른 글
[백준 BoJ] 2636 - 치즈 (0) | 2022.03.19 |
---|---|
[백준 BoJ] 3055 - 탈출 (0) | 2022.03.18 |
[백준 BoJ] 24678 - 돌무더기 게임 1 (0) | 2022.03.13 |
[백준 BoJ] 1113 - 수영장 만들기 (0) | 2022.03.08 |
[백준 BoJ] 12582 - 1로 만들기 2 (0) | 2022.03.08 |
Comments