黑白图像

输入一个n*n的黑白图像(1表示黑色,0表示白色),任务是统计其中八连块的个数。如果两个黑格子有公共边或者公共顶点,就说它们属于同一个八连块。

(题意是让求连在一起的块有几个,图见书本)

SamInput

6 100100 001010 000000 110000 111000 010100

 1 #include<iostream>
 2 using namespace std;
 3 const int MAXN=30;
 4 int mat[MAXN][MAXN],vis[MAXN][MAXN];
 5 void dfs(int x,int y)
 6 {
 7     if(!mat[x][y]||vis[x][y])//当前格子为白色,或者曾经访问过这个格子,白色用0表示,黑色用1表示
 8         return;
 9     vis[x][y]=1;//标记x,y已被访问过
10         dfs(x-1,y-1);dfs(x-1,y);dfs(x-1,y+1);//访问周围的八个格子
11         dfs(x,y-1);             dfs(x,y+1);
12         dfs(x+1,y-1);dfs(x+1,y);dfs(x+1,y+1);
13 }
14 int main()
15 {   int n;
16     char s[MAXN];//此处若定义string s 将会闪退
17     memset(mat,0,sizeof(mat));//作用是把数组mat清零
18     memset(vis,0,sizeof(vis));
19     cin>>n;
20     for(int i=0;i<n;i++)
21     {
22         scanf("%s",s);
23         for(int j=0;j<n;j++)
24             mat[i+1][j+1]=s[j]-'0';//把图像像中间移动一点,空出一圈白格子
25     }
26     int count=0;
27     for(int m=1;m<=n;m++)
28         for(int j=1;j<=n;j++)
29           if(mat[m][j]&&!vis[m][j])
30           {
31               count++;//找到没有访问过得黑格子
32               dfs(m,j);
33           }
34         cout<<count<<endl;
35         return 0;
36 }
View Code
原文地址:https://www.cnblogs.com/firstsy0709/p/3641594.html