【DFS题解】 Counting Stars

No.1  题意

原题:

eople generally don’t care to give attention to stars in a moonlit night. In most cases the attentiongoes towards the moon. Sadly, you have to write a program now that can count the stars in the sky. For this problem a sky is a two dimensional grid. Empty pixel is denoted by a ‘.’ (ASCII value 46) and a non-empty pixel is denoted by a ‘’ (ASCII value 42). As a star is a very small object so it cannot occupy more than one pixel and in our sky two stars are never adjacent. So two or more adjacent nonempty pixels can denote some larger objects like moon, comet, sun or UFOs but they never represent a star. All the eight possible pixels around a pixel are adjacent to it. In the figure below the black pixel at the center have eight adjacent pixels. Of them three pixels are non-empty

Input
The input file contains at most 1000 sets of inputs. The description of each set is given below:
    Each set starts with two integer number r and c (0 < r, c < 101), which indicates the row and column number of the image to follow. Next r rows describe the sky as mentioned in the problem statement. Input is terminated by a line containing two zeroes.
Output
For each set of input produce one line of output. This line contains a decimal integer which denotes the number of stars in the given sky.


中文,一句话:给出一个含有‘ * '的矩阵,求联通的' * '块中只含有一个' * '的版块的个数。


No.2 思路

看到矩阵,就应该想到用深度优先搜索,也就是DFS。我们可以从矩阵的左上角开始搜,每搜出一个' * '就判断它周围的八个方向是否也有' * '。如果是,那就不管,否则把答案加一。最后输出答案即可。

No.3 完整代码

#include <bits/stdc++.h>
using namespace std;
char map1[105][105];
const int d1[]={1,1,1,0,0,-1,-1,-1};
const int d2[]={-1,0,1,-1,1,-1,0,1};
int main(){
    int n,c;
    while(~scanf("%d%d",&n,&c)&&(n||c)){//多组输入,需判断。
        memset(map1,0,sizeof(map1));//多组输入,需把地图清空
        for(int i=1;i<=n;i++){
            scanf("%s",map1[i]+1);
    }
        int ans=0;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=c;j++){
                if(map1[i][j]=='*'){//找到1个'*',开始判断它周围是否有'*'
                    int flag=1;//标记是否有' * '
                    for(int k=0;k<8;k++){
                        if(map1[i+d1[k]][j+d2[k]]=='*'){
                            flag=0;//有则跳过
                            break;
                        }
            }
                    ans+=flag;//无则答案加一
                }
        }
        }
        printf("%d\n",ans);
    }
    return 0;
}

No.4 总结 

此题不是很难,只是对DFS深搜的基本应用,希望题解能对读者们有帮助。


 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值