Description
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).
Sample Input
5 6
......
..*...
.****.
..*...
..*...
Sample Output
YES
核心思想:
此题算不上搜索题,算是暴力枚举吧。
黑色表示非空,白色表示空白。
1、读入数据时用sum记录全部黑块的数量。
2、枚举每一个位置,判断此处以及相邻的上下左右四点是否都是黑色,若是,则将此处作为十字架中心并立即结束此步。此步只需要找一个中心,因为有两个中心一定NO。
3、以此中心为起点,分别向四个方向遍历,直到遇见空白或者边界为止,用cnt记录下此十字架的黑块数量。
4、若sum==cnt,则YES,否则NO。
代码如下:
#include<cstdio>
#include<iostream>
using namespace std;
typedef long long ll;
const int N=550;
char G[N][N];
int x,y,sum;
//判断此点是实心还是空心
bool pd(int x,int y)
{
if(G[x][y]=='*')
return 1;
return 0;
}
//寻找一个中心
bool find(int h,int w)
{
for(int i=1; i<h-1; i++)
for(int j=1; j<w-1; j++)
if(pd(i,j)&&pd(i-1,j)&&pd(i+1,j)&&pd(i,j-1)&&pd(i,j+1))
{
x=i;
y=j;
return 1;
}
return 0;
}
int main()
{
int h,w;
//输入
scanf("%d%d",&h,&w);
for(int i=0; i<h; i++)
{
scanf("%s",G[i]);
for(int j=0;j<w;j++)
if(G[i][j]=='*')
sum++;
}
//寻找中心
if(!find(h,w))
{
printf("NO\n");
return 0;
}
int k,cnt=1;//算上中心的一个点
//向上找
k=x-1;
while(k>=0&&G[k][y]=='*')
{
cnt++;
k--;
}
//向下找
k=x+1;
while(k<h&&G[k][y]=='*')
{
cnt++;
k++;
}
//向左找
k=y-1;
while(k>=0&&G[x][k]=='*')
{
cnt++;
k--;
}
//向右找
k=y+1;
while(k<w&&G[x][k]=='*')
{
cnt++;
k++;
}
//输出
if(sum==cnt)
printf("YES\n");
else
printf("NO\n");
return 0;
}