코딩공작소

[백준]아기상어(3) 본문

알고리즘/그래프

[백준]아기상어(3)

안잡아모찌 2019. 9. 28. 17:18

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

 

16236번: 아기 상어

N×N 크기의 공간에 물고기 M마리와 아기 상어 1마리가 있다. 공간은 1×1 크기의 정사각형 칸으로 나누어져 있다. 한 칸에는 물고기가 최대 1마리 존재한다. 아기 상어와 물고기는 모두 크기를 가지고 있고, 이 크기는 자연수이다. 가장 처음에 아기 상어의 크기는 2이고, 아기 상어는 1초에 상하좌우로 인접한 한 칸씩 이동한다. 아기 상어는 자신의 크기보다 큰 물고기가 있는 칸은 지나갈 수 없고, 나머지 칸은 모두 지나갈 수 있다. 아기 상어는 자신의 크

www.acmicpc.net

매번 풀어도 재밌는 문제. bfs+vector(sort) or Priority Queue를 이용하는 문제이다. 

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
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
 
struct INFO {
    int r, c;
};
 
int N, R, C, ans = 0, SZ = 2, Eaten = 0;
int map[20][20],dis[20][20];
int dr[] = { 0,0,-1,1 }, dc[] = { 1,-1,0,0 };
queue<INFO> q; //상어의 위치
vector<INFO> v; //물고기들의 위치
 
bool cmp(INFO a, INFO b) {
    if (a.r < b.r) return true;
    else if (a.r > b.r) return false;
    else {
        if (a.c < b.c) return true;
        else return false;
    }
}
 
void bfs() {
    while (!q.empty()) {
        int qlen = q.size();
        while (qlen--) {
            int r = q.front().r, c = q.front().c; q.pop();
            for (int i = 0; i < 4; i++) {
                int nr = r + dr[i], nc = c + dc[i];
                if (nr < 0 || nc < 0 || nr >= N || nc >= N || dis[nr][nc] != -1 || map[nr][nc]>SZ)continue;
                if (map[nr][nc] == 0 || map[nr][nc] == SZ) {
                    q.push({ nr,nc }); dis[nr][nc] = dis[r][c] + 1;
                }
                else if (map[nr][nc] < SZ) {
                    q.push({ nr,nc }); v.push_back({ nr,nc }); dis[nr][nc] = dis[r][c] + 1;
                }
            }
        }
        if (v.empty()) continue;
        sort(v.begin(), v.end(), cmp);
        ans += dis[v[0].r][v[0].c];
        Eaten++; map[v[0].r][v[0].c] = 0;
        if (Eaten == SZ) SZ++, Eaten = 0;
        while (!q.empty())q.pop(); q.push({ v[0].r,v[0].c }); //비워주기
        memset(dis, -1sizeof(dis)); dis[v[0].r][v[0].c] = 0;
        v.clear();
    }
    printf("%d\n", ans);
}
 
void solve() {
    memset(dis, -1sizeof(dis));
    q.push({ R,C }); dis[R][C] = 0;
    bfs();
}
 
int main()
{
    ios::sync_with_stdio(false); cin.tie(NULL);
    cin >> N;
    for (int i = 0; i < N; i++for (int j = 0; j < N; j++) {
        cin >> map[i][j];
        if (map[i][j] == 9) R = i, C = j, map[i][j] = 0;
    }
    solve();
    return 0;
}
cs

'알고리즘 > 그래프' 카테고리의 다른 글

[백준]영역구하기  (0) 2019.10.08
[백준]낚시왕(2)  (0) 2019.09.28
[SWEA]탈주범검거  (0) 2019.09.28
[백준]벽부수고이동하기  (0) 2019.09.21
[백준]게리맨더링  (0) 2019.09.21