程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> UVA 572 Oil Deposits油田(DFS求連通塊),depositsdfs

UVA 572 Oil Deposits油田(DFS求連通塊),depositsdfs

編輯:C++入門知識

UVA 572 Oil Deposits油田(DFS求連通塊),depositsdfs


UVA 572     DFS(floodfill)  用DFS求連通塊

Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

Description

Due to recent rains, water has pooled in various places in Farmer John's field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water ('W') or dry land ('.'). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors. 

Given a diagram of Farmer John's field, determine how many ponds he has.

Input

* Line 1: Two space-separated integers: N and M 

* Lines 2..N+1: M characters per line representing one row of Farmer John's field. Each character is either 'W' or '.'. The characters do not have spaces between them.

Output

* Line 1: The number of ponds in Farmer John's field.

Sample Input

10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.

Sample Output

3

Hint

OUTPUT DETAILS: 

There are three ponds: one in the upper left, one in the lower left,and one along the right side.

 

題解:輸入m行n列的字符矩陣,統計字符“W”組成多少個八連塊。如果兩個字符“W”所在的格子相鄰(橫,豎或者對角線方向),就說它們屬於同一個八連塊,采用二重循環來找。

        這就是連通塊原理;每訪問一次“W”,就給它寫上標記的編號,方便檢查。

 

AC代碼:

#include<cstdio>
#include<cstring>
const int maxn=1000+5;
char tu[maxn][maxn];  //輸入圖的數組
int m,n,idx[maxn][maxn]; //標記數組

void dfs(int r,int c,int id)
{
    if(r<0||r>=m||c<0||c>=n)
        return;
    if(idx[r][c]>0||tu[r][c]!='W')
        return;
    idx[r][c]=id;
    for(int dr=-1; dr<=1; dr++)    
        for(int dc=-1; dc<=1; dc++)   // 尋找周圍八塊
            if(dr!=0||dc!=0)
                dfs(r+dr,c+dc,id);
}
int main()
{
    int i,j;
    while(scanf("%d%d",&m,&n)==2&&m&&n)
    {
        for(i =0; i<m; i++)
            scanf("%s",tu[i]);
        memset(idx,0,sizeof(idx));
        int q=0;
        for(i=0; i<m; i++)
            for(j=0; j<n; j++)
                if(idx[i][j]==0&&tu[i][j]=='W')
                    dfs(i,j,++q);
        printf("%d\n",q);
    }
    return 0;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved