반응형

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

 

2665번: 미로만들기

첫 줄에는 한 줄에 들어가는 방의 수 n(1 ≤ n ≤ 50)이 주어지고, 다음 n개의 줄의 각 줄마다 0과 1이 이루어진 길이가 n인 수열이 주어진다. 0은 검은 방, 1은 흰 방을 나타낸다.

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. dijkstra를 이용하여 흰 방을 지날 때의 가중치는 1, 검은 방을 지날 때는 가중치 10000을 주어서 도착점에 도착했을 때 이동 거리를 10000으로 나눈 값을 출력합니다.

 

[ 소스코드 ]

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<iostream>
#include<queue>
 
using namespace std;
 
int n;
char arr[51][51];
int visited[50][50];
int dy[4= { -1,1,0,0 };
int dx[4= { 0,0,-1,1 };
 
struct node {
    int y;
    int x;
    int dist;
};
 
struct cmp {
    bool operator()(node right, node left) {
        return left.dist < right.dist;
    }
};
 
int main()
{
    scanf("%d"&n);
 
    for (int i = 0; i < n; i++) {
        scanf("%s", arr[i]);
        for (int j = 0; j < n; j++) {
            visited[i][j] = 987654321;
        }
    }
 
    priority_queue<node, vector<node>, cmp> pq;
 
    pq.push({ 0,0,0 });
    visited[0][0= 0;
 
    while (!pq.empty()) {
        const int y = pq.top().y;
        const int x = pq.top().x;
        const int dist = pq.top().dist;
        pq.pop();
 
        if (y == n - 1 && x == n - 1) {
            printf("%d", dist / 10000);
        }
 
        for (int i = 0; i < 4; i++) {
            const int yy = y + dy[i];
            const int xx = x + dx[i];
 
            if (yy >= 0 && yy < n && xx >= 0 && xx < n) {
                if (arr[yy][xx] == '1') {    //흰 방
                    if (visited[yy][xx] > dist + 1) {
                        visited[yy][xx] = dist + 1;
                        pq.push({ yy,xx,dist + 1 });
                    }
                }
                else {        //검은 방
                    if (visited[yy][xx] > dist + 10000) {
                        visited[yy][xx] = dist + 10000;
                        pq.push({ yy,xx,dist + 10000 });
                    }
                }
            }
        }
    }
}
cs
반응형

+ Recent posts