![[백준 C++] 2178 : 미로 탐색](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FcJQflk%2FbtsKMGoxzSt%2FvBmdhFH5EgH5iLqXeOBFak%2Fimg.png)
[백준 C++] 2178 : 미로 탐색CSE/코딩 문제풀이2024. 11. 17. 13:41
Table of Contents
https://www.acmicpc.net/problem/2178
최소 칸 수를 확인하기 위해서 DFS보다는 BFS로 푸는 것이 좋다고 하여, BFS로 풀어보았다.
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
vector<string> maze;
vector<vector<bool>> visited;
vector<vector<int>> answer;
int N, M;
int dx[4] = { -1, 0, 1, 0 };
int dy[4] = { 0, 1, 0, -1 };
void bfs()
{
queue<pair<int, int>> que;
int x, y = 0;
visited[0].at(0) = true;
answer[0].at(0) = 1;
que.push(make_pair(0, 0));
while (!que.empty())
{
y = que.front().first;
x = que.front().second;
que.pop();
for (int i = 0; i < 4; i++)
{
int nextY = y + dy[i];
int nextX = x + dx[i];
if ((nextX >= 0 && nextX < M) && (nextY >= 0 && nextY < N) && maze[nextY].at(nextX) == '1' && !visited[nextY].at(nextX))
{
visited[nextY].at(nextX) = true;
answer[nextY].at(nextX) = answer[y].at(x) + 1;
que.push(make_pair(nextY, nextX));
}
}
}
}
int main()
{
cin >> N >> M;
maze = vector<string>(N, "");
visited = vector<vector<bool>>(N, vector<bool>(M, false));
answer = vector<vector<int>>(N, vector<int>(M, 0));
for (int i = 0; i < N; i++)
{
string input;
cin >> input;
maze[i] = input;
}
bfs();
cout << answer[N - 1].at(M - 1) << '\n';
return 0;
}
이 코드에서 가장 중요한 부분은 answer배열이다.
BFS로 모든 구간에 방문함과 동시에 그 전까지 지나왔던 구간의 수를 answer배열에 저장하여 현재 구간까지 도달하였을 때 몇 개의 구간을 지나왔는지 확인할 수 있게 하였다.
'CSE > 코딩 문제풀이' 카테고리의 다른 글
[백준 C++] 7562 : 나이트의 이동 (0) | 2024.11.19 |
---|---|
[백준 C++] 1679 : 숨바꼭질 (0) | 2024.11.18 |
[백준 C++] 1012 : 유기농 배추 (2) | 2024.11.16 |
[백준 C++] 2667 : 단지번호붙이기 (0) | 2024.11.15 |
[백준 C++] 2606 : 바이러스 (2) | 2024.11.14 |
@NiffJB :: 개발하는 니프
CSE & GAME 개발 블로그
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 부탁드립니다!