danbibibi
article thumbnail

1. 문제

문제 바로가기> BOJ 2178번: 미로 탐색

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

 

2. 풀이

BFS를 이용하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구할 수 있다!

<cpp />
#include<iostream> #include<queue> #define MAX 101 #define INF 987654321 using namespace std; int N, M; int maze[MAX][MAX]; int dist[MAX][MAX]; int dy[] = {-1,1,0,0}; int dx[] = {0,0,-1,1}; void input(){ cin >> N >> M; string str; for(int i=1; i<=N; i++){ cin >> str; for(int j=1; j<=M; j++) { maze[i][j] = str[j-1]-'0'; dist[i][j] = INF; } } } void solution(){ queue<pair<int, int>> q; q.push({1, 1}); dist[1][1] = 1; while (!q.empty()){ int y = q.front().first; int x = q.front().second; q.pop(); for(int d=0; d<4; d++){ int ny = y + dy[d]; int nx = x + dx[d]; if(ny<1 || ny>N ||nx<1 || nx>M) continue; if(maze[ny][nx]==0 || dist[ny][nx]!=INF) continue; dist[ny][nx] = dist[y][x]+1; q.push({ny,nx}); } } cout << dist[N][M]; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); input(); solution(); }

'문제 풀이 > 백준' 카테고리의 다른 글

BOJ 10021번: Watering the Fields  (0) 2022.12.04
BOJ 9465번: 스티커  (0) 2022.12.03
BOJ 1260번: DFS와 BFS  (0) 2022.12.02
BOJ 15591번: MooTube (Silver)  (1) 2022.12.02
BOJ 2579번: 계단 오르기  (0) 2022.11.30
profile

danbibibi

@danbibibi

꿈을 꾸는 시간은 멈춰 있는 것이 아냐 두려워하지 마 멈추지 마 푸른 꿈속으로