1. 程式人生 > >dfs_Oil Deposits HDU - 1241

dfs_Oil Deposits HDU - 1241

題目:

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. 

Output

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

題目大意是:

  t組測試資料,每組輸入n,m作為行和列,依次輸入元素。最終判斷有多少個連在一起的@.

*@*@*
**@**
*@*@*
有一組@連線在一起

****@
*@@*@
*@**@
@@@*@
@@**@
有兩組@連線在一起

演算法:dfs

程式碼:

#include<iostream>
using namespace std;
char a[101][101];   //陣列作為輸入儲存陣列
int m,n; 
void dfs(int x,int y)
{
    int tx,ty;  //tx ty代表下一個元素
    a[x][y]='*';  //搜尋到這一個元素,那麼這個元素標記為*,防止下一次dfs重複搜尋此元素
    for(int dx=-1;dx<=1;dx++)
        for(int dy=-1;dy<=1;dy++) //因為要搜尋8個方向 所以-1到1
        {
            tx=dx+x;ty=dy+y;    //tx是下一個點
            if(tx<1 || tx>n || ty<1 || ty>m) continue; //小與1大於m或者n說明搜尋到了矩陣外邊
            if(a[tx][ty]=='@')    dfs(tx,ty);//如果下一個點是@那麼繼續搜尋這個點
        }
    return;
}
int main()
{
    int s;
    while(cin>>n>>m)
    {
        if(n==0) break; //如果輸入m==0 n==0 則要退出輸入
        s=0; //一定要讓s=0,因為每一次while迴圈都是一次新的計數 
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                cin>>a[i][j];      //依次輸入元素
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                if(a[i][j]=='@') {dfs(i,j);s++;}           //如果這個元素是@n,那麼開始深搜,如果搜尋結束返回到s++; 那麼@組數加1 
        cout<<s<<endl;
        
    } 
    
    return 0;
}