Uva 572 Solution

#include<bits/stdc++.h>
#define pii pair<int, int>
#define N 103
using namespace std;

int x[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int y[] = {-1, 0, 1, -1, 1, -1, 0, 1};

int row, column, v[N][N];
char a[N][N];

bool check(int r, int c)
{
return (r>=0) && (r<row) && (c>=0) && (c<column);
}

void bfsvisit(int x1, int y1)
{
v[x1][y1] = 1;
queue<pii>q;

q.push(pii(x1, y1));

while(!q.empty())
{
pii r = q.front();
q.pop();

for(int i=0;i<8;i++)
{
int tx = r.first + x[i];
int ty = r.second + y[i];

if(check(tx, ty) && a[tx][ty] == '@' && v[tx][ty] == 0)
{
v[tx][ty] = 1;
q.push(pii(tx, ty));
}
}
}
}

int main()
{
while(cin >> row >> column)
{
if(row == 0 && column == 0)
break;

for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
a[i][j] = '\0';
v[i][j] = 0;
}
}

for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
cin >> a[i][j];
}
int cnt = 0;
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
if(a[i][j] == '@' && v[i][j] == 0)
{
cnt++;
bfsvisit(i, j);
}
}
}
cout << cnt << "\n";
}

return 0;
}

Comments