유기농 배추 풀이
같은 문제이다. 먼저 풀어보고 푸는것을 추천한다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
using namespace std;
#define endl "\n"
#define MAX 50+1
int dy[] = { -1,-1, 0, 1, 1, 1, 0, -1 };
int dx[] = { 0, 1, 1, 1, 0, -1, -1, -1 };
bool board[MAX][MAX];
bool visited[MAX][MAX];
int ans;
int w, h;
void dfs(int y, int x) {
visited[y][x] = true;
for (int i = 0; i < 8; i++)
{
int nx = dx[i] + x;
int ny = dy[i] + y;
if (nx < 1 || nx > w || ny < 1 || ny > h)
{
continue;
}
if (board[ny][nx] && !visited[ny][nx])
{
dfs(ny, nx);
}
}
}
void reset() {
ans = 0;
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
board[i][j] = false;
visited[i][j] = false;
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
//ifstream cin; cin.open("input.txt");
while (true)
{
reset();
cin >> w >> h;
if (w == 0 && h == 0)
{
break;
}
for (int i = 1; i <= h; i++)
{
for (int j = 1; j <= w; j++)
{
cin >> board[i][j];
}
}
for (int i = 1; i <= h; i++)
{
for (int j = 1; j <= w; j++)
{
if (board[i][j] && !visited[i][j])
{
ans++;
dfs(i, j);
}
}
}
cout << ans<<endl;
}
}