백준 알고리즘/BFS
아기상어 C++
by paysmile
2021. 1. 3.
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int MAX = 21;
int map[MAX][MAX];
int n, atenumber = 0;
int sharksize = 2;
pair<int, int> sharkloc;
pair<int, pair<int, int>> feed;
int answer = 0;
struct Move {
int x, y;
};
Move mv[4] = { { 1,0 },{ -1,0 },{ 0,1 },{ 0,-1 } };
void bfs(pair<int, int> loc, int count) {
int visited[MAX][MAX];
queue <pair<int, pair<int, int>>> q;
memset(visited, -1, sizeof(visited));
q.push(make_pair(0, loc));
visited[loc.first][loc.second] = 1;
while (!q.empty()) {
loc = q.front().second;
int count = q.front().first;
q.pop();
if (!(feed.first >= count))
continue;
for (int k = 0; k < 4; k++) {
int movei = loc.first + mv[k].x;
int movej = loc.second + mv[k].y;
pair<int, int> moveloc = make_pair(movei, movej);
if (movei >= 0 && movei < n && movej >= 0 && movej < n && visited[movei][movej] != 1) {
if (!((movei == sharkloc.first) && (movej == sharkloc.second))) {
if (map[movei][movej] == 0) {
q.push(make_pair(count + 1, make_pair(movei, movej)));
visited[movei][movej] = 1;
}
else if (map[movei][movej] < sharksize) {
//먹을 수 있음
if (feed.first > count + 1)
feed = make_pair(count + 1, make_pair(movei, movej));
else if (feed.first == count + 1) {
if ((feed.second.first > movei) || ((feed.second.first == movei) && (feed.second.second > movej)))
feed = make_pair(count + 1, make_pair(movei, movej));
}
}
//지나갈 수만 있음
else if (map[movei][movej] == sharksize) {
q.push(make_pair(count + 1, make_pair(movei, movej)));
visited[movei][movej] = 1;
}
//지나갈 수도 없음 -> 탐색 안함
}
}
}
}
}
int main(void) {
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)
sharkloc = make_pair(i, j);
}
}
bool flag = true;
while (flag) {
feed = make_pair(10000, make_pair(21, 21));
bfs(sharkloc, 0);
//상어 크기 증가 필요
if (!((feed.second.first == 21) && (feed.second.second == 21))) {
map[sharkloc.first][sharkloc.second] = 0;
sharkloc = make_pair(feed.second.first, feed.second.second);
atenumber++;
map[feed.second.first][feed.second.second] = 0;
map[sharkloc.first][sharkloc.second] = 9;
answer += feed.first;
}
else {
flag = false;
}
if (atenumber == sharksize) {
sharksize++;
atenumber = 0;
}
}
cout << answer << endl;
return 0;
}