티스토리 뷰
- DFS
#include <cstdio>
#include <iostream>
using namespace std;
const int MAX = 60;
int w,h;
int map[MAX][MAX];
int check[MAX][MAX];
int dx[8] = {-1,-1,0,1,1,1,0,-1};
int dy[8] = {0,1,1,1,0,-1,-1,-1};
void dfs(int x, int y, int cnt)
{
check[x][y] = cnt;
for(int k = 0; k < 8; k++)
{
int nx = x + dx[k];
int ny = y + dy[k];
if(nx >= 0 && nx < h && ny >= 0 && ny < w)
{
if(map[nx][ny] == 1 && check[nx][ny] == 0)
{
//printf("(%d,%d)\n", nx, ny);
dfs(nx, ny, cnt);
}
}
}
}
int main()
{
while(1)
{
scanf("%d %d", &w, &h); //5 4
if(w == 0 && h == 0) break;
//초기화
for(int i = 0; i < h; i++)
{
for(int j = 0; j < w; j++)
{
map[i][j] = 0;
check[i][j] = 0;
}
}
for(int i = 0; i < h; i++)
{
for(int j = 0; j < w; j++)
{
scanf("%d", &map[i][j]);
}
}
int cnt = 0;
for(int i = 0; i < h; i++)
{
for(int j = 0; j < w; j++)
{
if(map[i][j] == 1 && check[i][j] == 0)
{
dfs(i, j, ++cnt);
}
}
}
printf("%d\n", cnt);
}
return 0;
}
'PS > BOJ' 카테고리의 다른 글
[7576번] 토마토 (0) | 2019.10.12 |
---|---|
[2178번] 미로탐색 (0) | 2019.10.08 |
[2667번] 단지번호붙이기 (0) | 2019.10.07 |
[1707번] 이분 그래프 (0) | 2019.10.06 |
[11724번] 연결요소 (0) | 2019.10.06 |