본문 바로가기

알고리즘/SW EXPERT

1249.보급로

1249. 보급로


다익스트라를 이용해서 시작점에서 끝점까지 최단거리를 구하면 된다.


<정답 코드>


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
#include<iostream>
#include<queue>
using namespace std;
const int INF = 987654321;
int dx[4= { 0,0,1,-1 };
int dy[4= { 1,-1,0,0 };
int main()
{
    //freopen("input.txt", "r", stdin);
    int tc;
    cin >> tc;
    for (int t = 1; t <= tc; t++)
    {
        int map[101][101= { 0, };
        int dist[101][101= { 0, };
        int n;
        cin >> n;
        for (int i = 0; i<n; i++)
        {
            for (int j = 0; j<n; j++)
            {
                scanf("%1d"&map[i][j]);
                dist[i][j] = INF;
            }
        }
 
        priority_queue<pair<intpair<intint>>> q;
        dist[0][0= 0;
        q.push({ -dist[0][0],{ 0,0 } });
 
        while (!q.empty())
        {
            int cost = -q.top().first;
            int x = q.top().second.first;
            int y = q.top().second.second;
            q.pop();
 
            if (cost>dist[x][y])
            {
                continue;
            }
 
            for (int d = 0; d<4; d++)
            {
                int nx = x + dx[d];
                int ny = y + dy[d];
                int w = map[nx][ny];
                if (nx >= 0 && ny >= 0 && nx<&& ny<n)
                {
                    if (dist[nx][ny]>cost + w)
                    {
                        dist[nx][ny] = cost + w;
                        q.push({ -dist[nx][ny],{ nx,ny } });
                    }
                }
            }
        }
 
        cout << "#" << t << " " << dist[n - 1][n - 1<< "\n";
 
    }
 
    return 0;
}
cs


반응형

'알고리즘 > SW EXPERT' 카테고리의 다른 글

4193. 수영대회 결승전  (0) 2018.04.09
3977. 페르마의 크리스마스 정리  (0) 2018.04.06
2814. 최장 경로  (0) 2018.03.30
4112. 이상한 피라미드 탐험  (0) 2018.03.27
4111. 무선 단속 카메라  (0) 2018.03.27