HyeLog
๋ฐฑ์ค_17086_์๊ธฐ ์์ด2 ๋ณธ๋ฌธ
๐โ๏ธ ๋ฌธ์
https://www.acmicpc.net/problem/17086
17086๋ฒ: ์๊ธฐ ์์ด 2
์ฒซ์งธ ์ค์ ๊ณต๊ฐ์ ํฌ๊ธฐ N๊ณผ M(2 ≤ N, M ≤ 50)์ด ์ฃผ์ด์ง๋ค. ๋์งธ ์ค๋ถํฐ N๊ฐ์ ์ค์ ๊ณต๊ฐ์ ์ํ๊ฐ ์ฃผ์ด์ง๋ฉฐ, 0์ ๋น ์นธ, 1์ ์๊ธฐ ์์ด๊ฐ ์๋ ์นธ์ด๋ค. ๋น ์นธ๊ณผ ์์ด์ ์๊ฐ ๊ฐ๊ฐ ํ ๊ฐ ์ด์์ธ ์ ๋ ฅ๋ง
www.acmicpc.net
๐งฉ ์๊ณ ๋ฆฌ์ฆ
๊ฐ ์นธ์ ์์ ๊ฑฐ๋ฆฌ = ์๊ธฐ ์์ด๊น์ง์ ์ต์ ๊ฑฐ๋ฆฌ → BFS ์๊ณ ๋ฆฌ์ฆ
์๊ฐ๋ณต์ก๋: O((NM)^2) (BFS = O(NM))
2 ≤ N, M ≤ 50 → BFS ๊ฐ๋ฅ
๐ก ์์ด๋์ด
๋ชจ๋ ๋น ์นธ์ ๋ํด BFS๋ก ์์ ๊ฑฐ๋ฆฌ๋ฅผ ๊ณ์ฐํ๋ฉด์ ์ต๋๊ฐ์ ๊ฐฑ์
๐ฉ๐ป ์ฝ๋
#include <iostream>
#include <queue>
#include <vector>
#include <tuple>
#include <algorithm>
using namespace std;
int dx[8] = { 0,0,1,1,1,-1,-1,-1 };
int dy[8] = { 1,-1,1,-1,0,1,-1,0 };
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
// input
int n, m;
cin >> n >> m;
vector<vector<int>> a(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> a[i][j];
}
}
int ans = 0;
// BFS
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i][j] == 1) continue;
vector<vector<bool>> visited(n, vector<bool>(m, false));
vector<vector<int>> dist(n, vector<int>(m, 0));
// ์์ ๊ฑฐ๋ฆฌ ๊ณ์ฐ
if (!visited[i][j]) {
// BFS
queue<pair<int, int>> q;
q.push(make_pair(i, j));
visited[i][j] = true;
dist[i][j] = 0;
while (!q.empty()) {
int x, y;
tie(x, y) = q.front();
q.pop();
if (a[x][y] == 1) { // ์๊ธฐ ์์ด
if (dist[x][y] > ans) ans = dist[x][y];
break;
}
for (int i = 0; i < 8; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m) {
if (!visited[nx][ny]) {
q.push(make_pair(nx, ny));
visited[nx][ny] = true;
dist[nx][ny] = dist[x][y] + 1;
}
}
}
}
}
}
}
// output
cout << ans << '\n';
return 0;
}
'์๊ณ ๋ฆฌ์ฆ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค_17141_์ฐ๊ตฌ์2 (0) | 2022.07.14 |
---|---|
๋ฐฑ์ค_2234_์ฑ๊ณฝ (0) | 2022.07.08 |
๋ฐฑ์ค_5014_์คํํธ๋งํฌ (0) | 2022.07.06 |
๋ฐฑ์ค_14395_4์ฐ์ฐ (0) | 2022.07.02 |
๋ฐฑ์ค_10026_์ ๋ก์์ฝ (0) | 2022.07.02 |