九度OJ Oil Deposit

題目描述

時間限制:1 秒 內存限制:32 兆 特殊判題:否
題目描述:
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.
輸入:
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.
輸出:
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.
樣例輸入:
1 1
*
3 5
@@

@
@@*
1 8
@@@
5 5
****@
@@@
@
@
@@@@
@@
*@
0 0
樣例輸出:
0
1
2
2

題目大意

在給定的 n*m 圖中,確定有幾個@的塊。塊符合以下條件,其中的任意對@均互相直接或間接連通,兩個@直接相鄰或者對角相鄰即被視爲連通

思路分析

用遞歸實現圖的遍歷,注意和回溯區分開

代碼

#include<stdio.h>
#include<string.h>
using namespace std;
int m,n;
char str[101][101];
bool mark[101][101];
int go[][2]={
    1,0,
    -1,0,
    0,1,
    0,-1,
    1,1,
    1,-1,
    -1,-1,
    -1,1
};

void DFS(int x,int y){
    for(int i=0;i<8;i++){
        int nx=x+go[i][0];
        int ny=y+go[i][1];
        if(mark[nx][ny]==true)continue;
        if(nx>m-1||nx<0||ny>n-1||ny<0)continue;
        if(str[nx][ny]=='*')continue;
        mark[nx][ny]=true;
        DFS(nx,ny);
    }
    return;
}

int main(void){
    while(scanf("%d%d",&m,&n)!=EOF){
        if(m==0&&n==0)break;
        for(int i=0;i<m;i++)
            scanf("%s",str[i]);
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++){
                mark[i][j]=false;
            }
        int ans=0;
        for(int i=0;i<m;i++)
        for(int j=0;j<n;j++){
            if(str[i][j]=='*')continue;
            if(mark[i][j]==true)continue;
            DFS(i,j);
            ans++;
        }
        printf("%d\n",ans);
    }
}

注意

字符串的讀取
scanf("%c",&c)會把回車符讀進去
scanf("%c %c",&a,&b);用空格符作爲間隔符
scanf("%c%c",&a,&b);如果輸入 A空格,那麼打印出來a,b變量就分別是A和空格

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章