
#include <iostream>
#include <vector>
using namespace std;
int dx[8] = {1, -1, 0, 0, 1, -1, 1, -1};
int dy[8] = {0, 0, 1, -1, 1, 1, -1, -1};
void dfs(vector<vector<int>> &map, vector<vector<bool>> &visited, int x, int y, int h, int w) {
visited[x][y] = true;
// 8방향 탐색
for (int i = 0; i < 8; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < h && ny >= 0 && ny < w) {
if (!visited[nx][ny] && map[nx][ny] == 1) {
dfs(map, visited, nx, ny, h, w);
}
}
}
}
int main() {
while (true) {
int w, h;
cin >> w >> h;
if (w == 0 && h == 0) break; // 종료 조건
vector<vector<int>> map(h, vector<int>(w));
vector<vector<bool>> visited(h, vector<bool>(w, false));
// 지도 입력 받기
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> map[i][j];
}
}
int islandCount = 0;
// 모든 위치 탐색
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (map[i][j] == 1 && !visited[i][j]) {
dfs(map, visited, i, j, h, w);
islandCount++; // DFS 한 번 돌 때마다 섬 개수 증가
}
}
}
cout << islandCount << endl;
}
return 0;
}
DFS로 풀 수 있다. BFS로도 어렵지 않게 가능할 듯.
'알고리즘' 카테고리의 다른 글
| BOJ 2240: 자두나무 (c++) (0) | 2025.03.30 |
|---|---|
| BOJ 2467: 용액 (C++) (0) | 2025.01.26 |
| BOJ 1995: 필터 (C++) (0) | 2025.01.12 |