You have a given picture with size w×h. Determine if the given picture has a single “+” shape or not. A “+” shape is described below:
A “+” shape has one center nonempty cell.
There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction.
All other cells are empty.
Find out if the given picture has single “+” shape.
Input
The first line contains two integers h and w (1≤h, w≤500) — the height and width of the picture.
The i-th of the next h lines contains string si of length w consisting “.” and “" where “.” denotes the empty space and "” denotes the non-empty space.
Output
If the given picture satisfies all conditions, print “YES”. Otherwise, print “NO”.
You can output each letter in any case (upper or lower).
Examples
Note
In the first example, the given picture contains one “+”.
In the second example, two vertical branches are located in a different column.
In the third example, there is a dot outside of the shape.
In the fourth example, the width of the two vertical branches is 2.
In the fifth example, there are two shapes.
In the sixth example, there is an empty space inside of the shape.
思路:先将中心找到,然后沿着上下左右四个方向将符号为‘*’的都变为‘.’。最后遍历一遍字符数组,若再还有星号,则输出no否则输出yes。
#include<stdio.h>
int main()
{
int n,m,num=0,x,y,i,j,nx,ny;
char a[510][510];
scanf("%d %d",&n,&m);
getchar();
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
scanf("%c",&a[i][j]);
getchar();//注意每行完会有回车
}
for(i=0;i<n;i++)
for(j=0;j<m;j++)
if(a[i][j]=='*'&&a[i+1][j]=='*'&&a[i-1][j]=='*'&&a[i][j+1]=='*'&&a[i][j-1]=='*')//找到中心
{
x=i;y=j;num++;
}
nx=x;ny=y;
if(num==1) //中心只能有一个
{
while(a[x][y]=='*')//将中心上下左右方向的星号都变为‘.’
a[x++][y]='.';
x=nx;y=ny;
a[x][y]='*';
while(a[x][y]=='*')
a[x--][y]='.';x=nx;y=ny;
a[x][y]='*';
while(a[x][y]=='*')
a[x][y++]='.';x=nx;y=ny;
a[x][y]='*';
while(a[x][y]=='*')
a[x][y--]='.';
for(i=0;i<n;i++)//遍历一遍改变后的数组
{
for(j=0;j<m;j++)
{
if(a[i][j]=='*')
{
printf("NO\n");num=0;break;
}
}
if(num==0)
break;
}
if(num==1)
printf("YES\n");
}
else
printf("NO\n");
return 0;
}
注:1.注意字符数组的输入会有回车;
2.每次改变中心四个方向的符号后 x,y的只会改变。