UVA 572 - Oil Deposits

这道题是一道搜索题,要我们找有多少块不同的油田,@与其相邻的八个方向的@属于同一片油田,

我选择用dfs来做。

#include<stdio.h>
#include<string.h>
#define N 105
int map[N][N], vis[N][N];
char str[N];

int dx[] = { -1, 1, 0, 0, -1, -1, 1, 1};
int dy[] = { 0, 0, -1, 1, -1, 1, -1, 1};

void dfs( int x, int y)
{
int newx, newy;
for( int i = 0; i < 8; i ++)
{
newx = x + dx[i];
newy = y + dy[i];
if( map[newx][newy] && !vis[newx][newy])
{
vis[newx][newy] = 1;
dfs(newx, newy);
}
}
}

int main()
{
int m, n;
int i, j;
while( scanf( "%d%d", &m, &n) != EOF)
{
if( m == 0 && n == 0) break;
memset( map, 0, sizeof(map) );
memset( vis, 0, sizeof(vis) );
for( i = 1; i <= m; i ++)
{
scanf( "%s", str + 1);
for( j = 1; j <= n; j ++)
{
if( str[j] == '@')
map[i][j] = 1;
}
}
int cnt = 0;
for( i = 1; i <= m; i ++)
for( j = 1; j <= n; j ++)
{
if( map[i][j] && !vis[i][j])
{
cnt ++;
vis[i][j] = 1;
dfs( i, j);
}
}
printf( "%d\n", cnt);
}
return 0;
}


你可能感兴趣的:(uva)