본문 바로가기
알고리즘/BFS

9205 맥주 마시면서 걸어가기

by tryotto 2020. 1. 21.
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
71
72
#include <stdio.h>
#include <vector>
#include <utility>
#include <math.h>
#include <queue>
#include <string.h>
 
using namespace std;
 
int dist[105][105= { 0 };
 
void bfs(int n) {
    queue<int> q;
 
    int cur = 0;
    int chk[105= { 0 };
 
    chk[cur] = 1;
    q.push(cur);
 
    while (!q.empty()) {
        cur = q.front();
        q.pop();
        
        if (cur == n + 1) {
            printf("happy\n");
            return;
        }
 
        for (int i = 0; i < n + 2; i++) {
            if (chk[i] == 1 || dist[cur][i]>1000)
                continue;
            chk[i] = 1;
            q.push(i);
        }
    }
    printf("sad\n");
    return;
}
 
int main() {
    int t;
    scanf("%d"&t);
 
    while (t--) {
        int n;
        scanf("%d"&n);
 
        vector<pair<intint> > xy(n + 3);        
 
        for (int i = 0; i < n + 2; i++) {
            int x, y;
            scanf("%d %d"&x, &y);
 
            xy[i].first = x;
            xy[i].second = y;
        }
 
        // 거리 만들기
        memset(dist, 0sizeof(dist));
        for (int i = 0; i < n + 1; i++) {
            for (int j = i + 1; j < n + 2; j++) {
                int len = abs(xy[i].first - xy[j].first)
                    + abs(xy[i].second - xy[j].second);
                dist[i][j] = len;
                dist[j][i] = len;
            }
        }
 
        bfs(n);
    }
}
cs


간단한 문제였다.

각 노드들의 거리를 구하고,
시작 노드 idx=0, 끝 노드 idx=n+1 로 둔 다음에 bfs를 돌렸다.
생각보다 간단했다.
조금만 머리를 굴리면 됐다


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

6593 상범 빌딩  (0) 2020.03.12
1953 팀배분  (0) 2020.01.20
3184 양  (0) 2020.01.20
2251 물통  (0) 2020.01.20
12761 돌다리  (0) 2020.01.20