bfs로 먹을거 찾아보고 있으면 위치를 저장하고 그거 먹는 시간을 기준으로 짜른다.


먹이의 위치가 하나도 없으면 break


#include <iostream>
#include <queue>
#include <algorithm>
#include <memory.h>
using namespace std;
struct p {
    int x, y;
};
int main(void)
{
    ios::sync_with_stdio(false); cin.tie(NULL);
    int n, a[20][20], sx, sy, visit[20][20], dx[] = { 0,0,1,-1 }, dy[] = { 1,-1,0,0 };
    cin >> n;
    for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) {
        cin >> a[i][j];
        if (a[i][j] == 9) sx = i, sy = j, a[i][j] = 0;
    }
    int ans = 0, cur_size = 2, qidx = 0, cnt = 0;
    pair<int,int> qq[400];
    while (1) {
        memset(visit, -1sizeof(visit));
        queue<p> q;
        q.push({ sx,sy });
        visit[sx][sy] = ans;
        int mv = -1;
        qidx = 0;
        while (q.size()) {
            int x = q.front().x;
            int y = q.front().y;
            q.pop();
            if (mv != -1 && visit[x][y] >= mv) continue;
            for (int i = 0; i < 4++i) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                if (nx < 0 || ny<0 || nx >= n || ny >= n || a[nx][ny] > cur_size || visit[nx][ny] != -1continue;
                visit[nx][ny] = visit[x][y] + 1;
                if (a[nx][ny] && a[nx][ny] < cur_size) {
                    if (mv == -1) mv = visit[nx][ny];
                    qq[qidx++= { nx,ny };
                }
                else {
                    q.push({ nx,ny });
                }
            }
        }
        if (qidx == 0break;
        sort(qq, qq + qidx);
        a[qq[0].first][qq[0].second] = 0;
        cnt++;
        if (cnt == cur_size) cur_size++, cnt = 0;
        sx = qq[0].first; sy = qq[0].second;
        ans = visit[sx][sy];
    }
    cout << ans << '\n';
    return 0;
}
cs


'BOJ' 카테고리의 다른 글

5431 책 쌓기  (0) 2018.11.07
16235 나무 재테크  (0) 2018.10.22
15684 사다리 조작  (0) 2018.08.29
15686 치킨 배달  (0) 2018.08.29
15683 감시  (0) 2018.08.29

+ Recent posts