先将k周围标记,然后找出所有失败的情况。剩下的就是一定会成功的情况,对于每个‘*’,先判断左下是否已经放过兵,如果没有,在它右下放兵并标记,结果+1。如果它的右下无法放,在左下放兵并标记,结果+1。
#include <stdio.h>
#include <iostream>
using namespace std;
char bor[1005][1005];
int vis[1005][1005]={0};
int pass[1005][1005]={0};
int ans[1005][1005]={0};
int main()
{
int n;
int sum=0;
cin >> n;
getchar();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin >> bor[i][j];
if(bor[i][j]=='K')
{
pass[i-1][j-1]=1;
pass[i-1][j]=1;
pass[i-1][j+1]=1;
pass[i][j-1]=1;
pass[i][j+1]=1;
pass[i+1][j-1]=1;
pass[i+1][j]=1;
pass[i+1][j+1]=1;
}
}
getchar();
}
int flag=0;
for(int j=1;j<=n;j++)
{
if(bor[n][j]=='*'&&pass[n][j]==0)
{
flag=1;
break;
}
}
for(int i=1;i<n;i++)
{
for(int j=1;j<=n;j++)
{
if(bor[i][j]=='*'&&pass[i][j]==0&&bor[i+1][j-1]!='w')
{
if((j==1&&bor[i+1][j+1]=='*')||(j==n&&bor[i+1][j-1]=='*'))
{
flag=1;
break;
}
else if(bor[i+1][j-1]=='*'&&bor[i+1][j+1]=='*')
{
flag=1;
break;
}
else
{
if(bor[i+1][j+1]=='-')
{
sum++;
bor[i+1][j+1]='w';
}
else if(bor[i+1][j-1]=='-')
{
sum++;
bor[i+1][j-1]='w';
}
}
}
}
}
if(flag==1)
{
cout << -1;
}
else
{
cout << sum;
}
}