-
[백준 13565] 침투백준/BFS 2023. 9. 12. 20:43
그냥 전형적인 BFS 문제
BFS는 재귀보단 내부적으로 queue 써서 돌리는게 더 직관적이다
시작점을 희소행렬로 저장해두고 미리 시작점들을 queue에 넣고 BFS 돌려주면 됨
#include <iostream> #include <bitset> #include <vector> #include <queue> #define SIZE 1001 using namespace std; bitset<SIZE> map[SIZE]; bitset<SIZE> visited[SIZE]; vector<pair<int,int>> v; int dy[4] = { 0,-1,1,0 }; int dx[4] = { -1,0,0,1 }; int M, N; void solve() { queue<pair<int, int>> q; // 시작점 모두 넣기 for (int i = 0; i < v.size(); i++) { q.push(v[i]); visited[v[i].first][v[i].second] = 1; } bool isPossible = false; while (!q.empty()) { int y = q.front().first; int x = q.front().second; q.pop(); // 아래까지 도달했으면 종료 if (y == M - 1) { isPossible = true; break; } for (int i = 0; i < 4; i++) { int newy = y + dy[i]; int newx = x + dx[i]; // 갈 수 없거나 이미 방문했으면 스킵 if (newy < 0 || newx < 0 || newy >= M || newx >= N || visited[newy][newx]) continue; // 아직 방문하지 않은 갈 수 있는 곳이면 가보기 if (map[newy][newx] == 0) { visited[newy][newx] = 1; q.push(make_pair(newy, newx)); } } } if (isPossible) cout << "YES"; else cout << "NO"; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> M >> N; char x; // 시작점들 저장 for (int k = 0; k < N; k++) { cin >> x; map[0][k] = ((x == '0') ? 0 : 1); if (x == '0') v.push_back(make_pair(0,k)); } for (int i = 1; i < M; i++) { for (int k = 0; k < N; k++) { cin >> x; map[i][k] = ((x == '0') ? 0 : 1); } } solve(); return 0; }
'백준 > BFS' 카테고리의 다른 글
[백준 21922] 학부 연구생 민상 (0) 2024.01.17 [백준 7576] 토마토 (1) 2024.01.09 [백준 24444] 알고리즘 수업 - 너비 우선 탐색 1 (0) 2023.09.15 [백준 2573] 빙산 (0) 2023.07.07 [백준 2178] 미로 탐색 (0) 2023.05.12