반응형

www.acmicpc.net/problem/1261

 

1261번: 알고스팟

첫째 줄에 미로의 크기를 나타내는 가로 크기 M, 세로 크기 N (1 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 미로의 상태를 나타내는 숫자 0과 1이 주어진다. 0은 빈 방을 의미하고, 1은 벽을 의미

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
53
54
55
56
// https://chanhuiseok.github.io/posts/baek-17/
#include <iostream>
#include <queue>
#include <vector>
#define pii pair<intint>
#define rep(i,n) for(int i=1;i<=n;i++)
#define MAX 987654321
using namespace std;
int n, m, arr[101][101], dist[101][101];
int dx[] = { 010-1 };
int dy[] = { 10-10 };
queue<pii> q;
void bfs() {
    q.push({ 11 });
    dist[1][1= 0;
    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 <= m && ny > 0 && ny <= n) {
                // 1. 1 (벽)
                if (arr[nx][ny] == 1) {
                    if (dist[x][y] + 1 < dist[nx][ny]) {    // (현재 위치에서 다음 위치로 이동하는 비용) vs (이전에 찾아놓은 다음 위치로 이동하는 비용)
                        dist[nx][ny] = dist[x][y] + 1;
                        q.push({ nx, ny });
                    }
                }
                // 2. 0 (통로)
                else {
                    if (dist[x][y] < dist[nx][ny]) {        // (현재 위치에서 다음 위치로 이동하는 비용) vs (이전에 찾아놓은 다음 위치로 이동하는 비용)
                        dist[nx][ny] = dist[x][y];
                        q.push({ nx, ny });
                    }
                }
            }
        }
    }
}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> m;
    rep(i, m) {
        rep(j, n) {
            char c;
            cin >> c;
            arr[i][j] = c - '0';
            dist[i][j] = MAX;
        }
    }
    bfs();
    cout << dist[m][n];
}
cs
반응형

'백준 > 다익스트라' 카테고리의 다른 글

백준 1504  (0) 2021.02.21
백준 1238 [복습 필수]  (0) 2021.02.19
백준 1753 [복습 필수]  (0) 2021.02.19

+ Recent posts