只需要注意起始点不能是机关, 但是如果只有一个点的话, 起始点是可以是机关的
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define N 110
#define met(a, b) memset(a, b, sizeof(a))
using namespace std;
const int dir[8][2] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1,},{1,0},{1,1}};
struct node
{
int x, y, step;
}JG[N];
int n, m, k, vis[N][N];
char G[N][N];
bool Judge(int x, int y)
{
if(x>=1 && x<=n && y>=1 && y<=m && !vis[x][y] && (G[x][y]==‘.‘ || G[x][y]==‘@‘))
return 1;
return 0;
}
int BFS(int w)
{
node p, q;
p = JG[w];
p.step = 0;
queue<node>Q;
Q.push(p);
memset(vis, 0, sizeof(vis));
vis[p.x][p.y] = 1;
G[JG[w+1].x][JG[w+1].y] = ‘@‘;
while(Q.size())
{
p = Q.front(); Q.pop();
if(G[p.x][p.y]==‘@‘)
{
G[p.x][p.y] = ‘.‘;
return p.step;
}
for(int i=0; i<8; i++)
{
q.x = p.x + dir[i][0];
q.y = p.y + dir[i][1];
q.step = p.step + 1;
if(i==1 || i==3 || i==4 || i==6)
{
if(Judge(q.x, q.y))
{
vis[q.x][q.y] = 1;
Q.push(q);
}
}
else if(i==0)
{
if(Judge(q.x, q.y))
{
if(G[p.x-1][p.y]==‘#‘ && G[p.x][p.y-1]==‘#‘) continue;
vis[q.x][q.y] = 1;
Q.push(q);
}
}
else if(i==2)
{
if(Judge(q.x, q.y))
{
if(G[p.x-1][p.y]==‘#‘ && G[p.x][p.y+1]==‘#‘) continue;
vis[q.x][q.y] = 1;
Q.push(q);
}
}
else if(i==5)
{
if(Judge(q.x, q.y))
{
if(G[p.x+1][p.y]==‘#‘ && G[p.x][p.y-1]==‘#‘) continue;
vis[q.x][q.y] = 1;
Q.push(q);
}
}
else ///if(i==7)
{
if(Judge(q.x, q.y))
{
if(G[p.x+1][p.y]==‘#‘ && G[p.x][p.y+1]==‘#‘) continue;
vis[q.x][q.y] = 1;
Q.push(q);
}
}
}
}
return -1;
}
int main ()
{
int t;
scanf("%d", &t);
while(t--)
{
int i, ans, sum=0;
scanf("%d%d%d", &n, &m, &k);
memset(G, 0, sizeof(G));
for(i=1; i<=n; i++)
scanf("%s", G[i]+1);
scanf("%d%d", &JG[0].x, &JG[0].y);
for(i=1; i<=k; i++)
{
scanf("%d%d", &JG[i].x, &JG[i].y);
G[JG[i].x][JG[i].y] = ‘*‘;
}
if(G[JG[0].x][JG[0].y]==‘*‘ && k!=1)
{
printf("-1\n");
continue;
}
for(i=0; i<k; i++) ///第i次查找
{
ans = BFS(i);
if(ans==-1) break;
sum += ans;
}
if(ans==-1) printf("-1\n");
else printf("%d\n", sum);
}
return 0;
}