Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

차근차근

[백준 2178] 미로 탐색 본문

대학교/Algorithm

[백준 2178] 미로 탐색

SWKo 2020. 3. 3. 20:58

0. 제목

  • 백준 2178 미로 탐색
  • BOJ 2178 미로 탐색
  • C++ 2178 미로 탐색

1. 문제

https://www.acmicpc.net/problem/2178


2. 풀이

  • 최단거리 구하는 문제로 BFS를 사용하였다.
  • make_pair를 사용하여 좌표쌍을 큐에 push하였다.
  • BFS특성상 한단계씩 뻗어 나가기때문에 최단거리를 구하는데 적합하다.
  • 큐에는 탐색할 좌표들을 담아놓는다.
  • 큐에 있는 좌표가 더이상 주변의 탐색을 모두 끝낸 좌표일때 pop을 해준다.
  • dist배열의 값이 0이면 아직 방문하지 않은 것이고 1 이상이면 방문을 했다는 것이고 1이상의 숫자는 dist[i][j] 에 오기까지 거친 블록의 수이다.
  • 주의할 점으로는 입력을 받을때 연속해서 받기때문에 scanf("%1d", &arr[i][j])와 같이 입력받아야 한다.

3. 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <queue>
using namespace std;
 
int arr[101][101];
int dist[101][101];
int cnt;
int N, M;
queue<pair<intint>> q;
 
int dx[4= {0,1,0,-1};
int dy[4= {1,0,-1,0};
 
void bfs(int a, int b){
    q.push(make_pair(a, b));
    dist[a][b]++;
    while(!q.empty()){
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        
        for(int i = 0; i < 4; i++){
            int nx = x + dx[i];
            int ny = y + dy[i];
            
            if(nx <= 0 || nx > N || ny <= 0 || ny > M) continue;
            if(dist[nx][ny] == 0 && arr[nx][ny] == 1){
                dist[nx][ny] = dist[x][y] + 1;
                q.push(make_pair(nx, ny));
            }
        }
    }
}
 
int main(int argc, const char * argv[]) {
    cin >> N >> M;
    for(int i = 1; i <= N; i++)
        for(int j = 1; j <= M; j++)
            scanf("%1d"&arr[i][j]);
 
    bfs(1,1);
    cout << dist[N][M] << '\n';
    
    return 0;
}
 
 

'대학교 > Algorithm' 카테고리의 다른 글

[백준 1931] 회의실배정  (0) 2020.03.06
[백준 1783] 병든 나이트  (0) 2020.03.06
[백준 7576] 토마토  (0) 2020.03.01
[백준 2022] 사다리  (0) 2020.02.29
[백준 2003] 수들의 합 2  (0) 2020.02.29
Comments