반응형

www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

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

www.acmicpc.net

 

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
47
48
49
50
51
52
#include <iostream>
#include <vector>
#include <queue>
#define pii pair<intint>
using namespace std;
int n, m, cnt;
int arr[100][100], visited[100][100];
int dx[] = { 001-1 };
int dy[] = { 1-100 };
queue<pii> q;
void bfs(int i, int j) {
    q.push({ i,j });
    visited[i][j] = 1;
    while (!q.empty()) {
        cnt++;
        // 단계별로 진행
        int size = q.size();
        while (size--) {
            int x = q.front().first;
            int y = q.front().second;
            // 끝에 도착
            if (x == n - 1 && y == m - 1) {
                cout << cnt;
                return;
            }
            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) {
                    if (!visited[nx][ny] && arr[nx][ny]) {
                        visited[nx][ny] = 1;
                        q.push({ nx, ny });
                    }
                }
            }
        }
    }
}
int main() {
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            char c;
            cin >> c;
            arr[i][j] = c - '0';
        }
    }
    bfs(0,0);
}
 
 
cs
반응형

'백준 > DFS, BFS' 카테고리의 다른 글

백준 14226 [복습 필수]  (0) 2021.02.19
백준 13913  (0) 2021.02.19
백준 1707  (0) 2021.02.19
백준 13023  (0) 2021.02.19
백준 2583  (0) 2021.02.03

+ Recent posts