欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【搜索】UVA572 - Oil Deposits 深搜

程序员文章站 2022-05-20 16:41:23
...

Description

The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits.GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil.A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.

Input

The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 ≤ m ≤ 100 and 1 ≤ n ≤ 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either ‘*’, representing the absence of oil, or ‘@’, representing an oil pocket.

Ouput

For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.

Sample Input

1 1
*
3 5
* @ * @ *
* * @ * *
* @ * @ *
1 8
@@ * * * * @ *
5 5
* * * * @
* @@ *@
* @ * * @
@@@ * @
@@ * * @
0 0

Sample Output

0
1
2
2

Explanation

深度优先搜索实现
对每个位置进行遍历,若该点为’@’,则标记且递归该点遍历其与其邻近的八个点,若为’@’继续标记且对其递归遍历,再继续遍历下一个位置,执行相同的操作

Code

#include <stdio.h>
#include <string.h>
#define maxn 100 + 5
int dir[8][2] = {-1, 0, 1, 0, 0, -1, 0, 1, -1, -1, -1, 1, 1, -1, 1, 1};
//方向数组,分别为上下左右 左上 右上 左下 右下
int vis[maxn][maxn]; //标记数组,标记某位置是否被连通过
char pic[maxn][maxn];//图
int m, n;
int judge(int x,int y){
    if(x >= 0 && x < m && y >= 0 && y < n && !vis[x][y])
        return 1;
    return 0;
}
void DFS(int x,int y){
    vis[x][y] = 1;
    for(int i = 0; i < 8; i++){
        int xx = x + dir[i][0];
        int yy = y + dir[i][1];
        if(judge(xx,yy) && pic[xx][yy] == '@'){
            DFS(xx,yy);//继续递归遍历
        }
    }
}
int main()
{
    while(scanf("%d%d",&m,&n)==2 && m && n){
        memset(vis, 0, sizeof(vis));
        for(int i = 0; i < m; i++)
            scanf("%s",pic[i]);
        int sum = 0;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(pic[i][j] == '@'){
                    if(!vis[i][j]){
                        DFS(i,j);
                        sum++;
                    }
                }
            }
        }
        printf("%d\n",sum);
    }


    return 0;
}