알고리즘
백준 17086번 아기 상어 2 C++
영춘권의달인
2022. 12. 15. 12:08
https://www.acmicpc.net/problem/17086
17086번: 아기 상어 2
첫째 줄에 공간의 크기 N과 M(2 ≤ N, M ≤ 50)이 주어진다. 둘째 줄부터 N개의 줄에 공간의 상태가 주어지며, 0은 빈 칸, 1은 아기 상어가 있는 칸이다. 빈 칸과 상어의 수가 각각 한 개 이상인 입력만
www.acmicpc.net
bfs
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int n, m;
int ans = 0;
int dRow[8] = { -1,-1,0,1,1,1,0,-1 };
int dCol[8] = { 0,1,1,1,0,-1,-1,-1 };
struct Info {
int row;
int col;
int dist;
};
vector<vector<bool>> found;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
found = vector<vector<bool>>(n, vector<bool>(m, false));
queue<Info> q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int state;
cin >> state;
if (state == 1) {
found[i][j] = true;
q.push({ i,j,0 });
}
}
}
while (!q.empty()) {
auto curr = q.front();
q.pop();
ans = max(ans, curr.dist);
for (int i = 0; i < 8; i++) {
int nextRow = curr.row + dRow[i];
int nextCol = curr.col + dCol[i];
if (nextRow < 0 || nextRow >= n) continue;
if (nextCol < 0 || nextCol >= m) continue;
if (found[nextRow][nextCol]) continue;
found[nextRow][nextCol] = true;
q.push({ nextRow,nextCol,curr.dist + 1 });
}
}
cout << ans;
}