看到这题目名字有点逗.
刚开始用bfs没成功,主要是不知道怎么判重,单纯判断是否访问过是不行的.
换成dfs过了.
注意边界是可以走的.
#include <iostream>
#include <cstdio>
#include <memory.h>
#include <queue>
using namespace std;
const int maxn=103;
int grid[maxn][maxn],di[]={0,0,1,-1},dj[]={1,-1,0,0},n,m,p,ti,tj;
bool vis[maxn][maxn];
bool dfs(int ci,int cj,int turns,int curd){
if(ci==ti&&cj==tj&&turns<=2){
return true;
}
if(turns>2)return false;
for (int i=0;i<4;++i){
int ni=ci+di[i],nj=cj+dj[i];
if(ni>=0&&ni<=n+1&&nj>=0&&nj<=m+1&&!vis[ni][nj]&&(grid[ni][nj]==0||ni==ti&&nj==tj)){
vis[ni][nj]=1;
if(curd!=-1&&curd!=i){
if(dfs(ni,nj,turns+1,i)){
return true;
}
}else {
if(dfs(ni,nj,turns,i)){
return true;
}
}
vis[ni][nj]=0;
}
}
return false;
}
int main(){
while (scanf("%d%d",&n,&m)){
if(!n&&!m)break;
memset(grid,0,sizeof(grid));
for (int i=1;i<=n;++i){
for (int j=1;j<=m;++j){
scanf("%d",&grid[i][j]);
}
}
int ans=0;
scanf("%d",&p);
while (p--){
int x1,y1,x2,y2;
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
if(grid[x1][y1]&&grid[x2][y2]&&grid[x1][y1]==grid[x2][y2]){
ti=x2,tj=y2;
memset(vis,0,sizeof(vis));
if(dfs(x1,y1,0,-1)){
ans+=2;
grid[x1][y1]=grid[x2][y2]=0;
}
}
}
printf("%d\n",ans);
}
return 0;
}