https://www.acmicpc.net/problem/4963
#include <iostream>
#include <vector>
using namespace std;
int w, h;
vector<vector<int>> map;
vector<vector<bool>> visited;
// 8방향 (상, 하, 좌, 우 + 대각선)
int dx[8] = { -1, -1, -1, 0, 0, 1, 1, 1 };
int dy[8] = { -1, 0, 1, -1, 1, -1, 0, 1 };
void DFS(int x, int y)
{
visited[y][x] = true;
for (int i = 0; i < 8; ++i)
{
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && ny >= 0 && nx < w && ny < h)
{
if (!visited[ny][nx] && map[ny][nx] == 1)
{
DFS(nx, ny);
}
}
}
}
int main()
{
while (true)
{
cin >> w >> h;
if (w == 0 && h == 0) break;
map = vector<vector<int>>(h, vector<int>(w));
visited = vector<vector<bool>>(h, vector<bool>(w, false));
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
cin >> map[y][x];
}
}
int islandCount = 0;
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
if (map[y][x] == 1 && !visited[y][x])
{
DFS(x, y);
++islandCount;
}
}
}
cout << islandCount << endl;
}
return 0;
}
백준 10799 (0) | 2025.04.09 |
---|---|
백준 2559 (0) | 2025.04.05 |
백준 //안전 영역 (0) | 2025.04.04 |
프로그래머스 바탕화면 정리 (0) | 2025.04.03 |
소수 구하기//백준 (0) | 2025.03.31 |