poj1562 DFS入门

K - 搜索

Crawling in process... Crawling failed Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u

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 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.

Output

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

题目大意:就是给你一个矩阵形地图,用@表示油井,*表示空白处,每一个油井周围那8个位置都算与他相邻,所有相邻的油井算作一个pocket,问有多少个pocket.

思路分析:这应该算是BFS题目中最简单的一类了,直接暴力过一遍,每次都从@进行遍历,计数加1,然后深搜将所有搜索到的@都标记为*,当所有的@都被标记,搜索结束,输出计数变量。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
const int maxn=105;
char ma[maxn][maxn];
int f[8][2]={{1,0},{-1,0},{0,1},{0,-1},{-1,-1},{-1,1},{1,-1},{1,1}};
int m,n;
int cnt,flag;
void dfs(int x,int y)
{
    if(!flag)
    flag=1,cnt++;
    ma[x][y]='*';
    for(int i=0;i<8;i++)
    {
        int a=x+f[i][0];
        int b=y+f[i][1];
        if(ma[a][b]=='@')
            dfs(a,b);
    }
}
int main()
{
    while(cin>>m>>n&&(m||n))
    {
        cnt=0;
        int i,j;
        for(i=1;i<=m;i++)
            for(j=1;j<=n;j++)
            cin>>ma[i][j];
        for(i=1;i<=m;i++)
        {
            for(j=1;j<=n;j++)
            {
                flag=0;
                if(ma[i][j]=='@')
                    dfs(i,j);
            }
        }
        cout<<cnt<<endl;
    }
}

人一我百,人百我千!

上一篇:/usr/include/glib-2.0/glib/gtypes.h:34:24: fatal error: glibconfig.h: No such file or directory


下一篇:SQL Server 随机数,随机区间,随机抽取数据rand(),floor(),ceiling(),round(),newid()函数等