BFS——BMW图形文字识别

有一些由“_"和"#"组成的图形,图形中由"#"拼成了"B"、"M"、"W"三种字母,。用程序识别这些字母,统计三个字母的个数。

___###############________________________________

___###################____________________________

___#####################__________________________
___#####_____________#####________________________
___#####_______________###________________________
___#####_______________###________________________
___#####_______________###________________________
___#####_____________#####________________________
___#####___________#####__________________________
___###################____________________________
___###################____________________________
___#####___________#######________________________
___#####_______________###________________________
___#####_______________#####______________________
___#####_______________#####______________________
___#####_______________#####______________________
___#####_______________#####______________________
___#####_____________#####________________________
___#######################________________________
___###################____________________________

1 0 0

先BFS判断联通块

在判断首行间隔数目

View Code
#include<stdio.h>
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;

int hash1[209][209];
int map[209][209];
int ne[209][209];
int diri[4]={0,-1,0,1};
int dirj[4]={-1,0,1,0};

int used[10099];

struct data
{
int ni,nj;
};

int n,m;

void bfs(int x,int y,int add)
{
queue<data>qq;
int i,j;
data f,s,t;
f.ni=x;
f.nj=y;
qq.push(f);
while(!qq.empty())
{
s=qq.front();
qq.pop();
for(i=0;i<=3;i++)
{
t.ni=s.ni+diri[i];
t.nj=s.nj+dirj[i];

if(t.ni>=1&&t.ni<=n&&t.nj>=1&&t.nj<=m&&(hash1[t.ni][t.nj]==0)&&map[t.ni][t.nj]==1)
{
hash1[t.ni][t.nj]=add;
qq.push(t);
}
}
}
}

int main()
{
char temp;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(hash1,0,sizeof(hash1));
memset(used,0,sizeof(used));

int i,j;
char ss[1009];
for(i=1;i<=n;i++)
{
//getchar();
scanf("%s",ss);
for(j=1;j<=m;j++)
{
temp=ss[j-1];
if(temp=='_')
map[i][j]=0;
else
map[i][j]=1;
}
}


int add=1;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(hash1[i][j]==0&&map[i][j]==1)
{
bfs(i,j,add);
add++;
}
}
}
/*
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
printf("%d",hash1[i][j]);
}
printf("\n");
}
*/

add=1;
int k;
int B=0,M=0,W=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(hash1[i][j]==0)continue;
if(used[hash1[i][j]]==1)continue;

add==hash1[i][j];

int temp=1;
for(k=j+1;k<=m;k++)
{
if(hash1[i][k]!=0&&hash1[i][k]!=add)
{
break;
}

if(hash1[i][k]!=0&&used[hash1[i][k]]==0)
{
if(hash1[i][k-1]==0)
temp++;
}

}
j=k;

used[add]=1;
if(temp==1)
{
// printf("%d %d\n",i,j);
B++;
}
if(temp==2)
M++;
if(temp==3)
W++;
add++;
}
}

printf("%d %d %d\n",B,M,W);

}
return 0;
}





原文地址:https://www.cnblogs.com/huhuuu/p/2404989.html