连连看的小游戏(只有4种牌),判断是否能全部消除。思路非常简单但是要注意减枝。
外层的DFS指定一张牌来想办法消除它,内层的BFS以指定的这张牌为起点,向四周扩展找到能和它配对的牌。然后每一对能消除的牌都考虑一遍。
1.连的线不能越界到格子外边;
2.有的牌只有奇数个,无解
3.出现了 A B 这种情况而且,AB分别只有两张,那么肯定无解;不加这个减枝会超时。
。。。。B A
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int mp[12][12],n,m,num[5],sum;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
bool flag,vis[11][11];
char str[12];
void Init()
{
memset(mp,0,sizeof mp);
memset(num,0,sizeof num);
sum = flag = 0;
}
struct Node
{
int x,y,turn,d;
Node(){}
Node(int a,int b,int c,int dd)
{x = a; y = b; turn = c; d = dd;}
};
bool inarea(int x,int y)
{
if(x<1||y<1||x>n||y>m) return false;
else return true;
}
void bfs(int x,int y,int w,Node *can,int &len)
{
memset(vis,0,sizeof vis);
queue<Node> Q;
Q.push(Node(x,y,0,-1));
vis[x][y] = 1;
while(!Q.empty())
{
Node u = Q.front();
Q.pop();
if(mp[u.x][u.y] == w)
{
can[++len].x = u.x;
can[len].y = u.y;
continue;
}
for(int i = 0; i < 4; i++)
{
int tx = u.x+dir[i][0],ty = u.y+dir[i][1],tturn = 0;
if(!inarea(tx,ty) || (mp[tx][ty] != -1&&mp[tx][ty] != w) || vis[tx][ty]) continue;
if(u.d == i||u.d == -1)
tturn = u.turn;
else tturn = u.turn+1;
if(tturn > 2) continue;
vis[tx][ty] = 1;
Q.push(Node(tx,ty,tturn,i));
}
}
}
bool check()
{
for(int i = 1; i < n; i++)
for(int j = 1; j < m; j++)
{
if(mp[i][j] != -1&&mp[i][j+1] != -1&&mp[i][j] != mp[i][j+1])
{
if(mp[i][j] == mp[i+1][j+1]&&mp[i][j+1] == mp[i+1][j]&&num[mp[i][j]] == 2&&num[mp[i][j+1]] == 2)
return false;
}
}
return true;
}
void dfs(int cur)
{
if(cur == 0)
{
flag = 1;
return;
}
if(flag) return;
if(!check()) return;//减枝
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
{
if(flag) return;
if(mp[i][j] != -1)
{
int w = mp[i][j],len = 0;
Node can[110];
mp[i][j] = -1;
bfs(i,j,w,can,len);//搜索能与(i,j)配对的牌
for(int k = 1; k <= len; k++)
{
mp[can[k].x][can[k].y] = -1;
num[w] -= 2;
dfs(cur-2);
num[w] += 2;
mp[can[k].x][can[k].y] = w;
}
mp[i][j] = w;
}
}
}
int main()
{
while(scanf("%d%d",&n,&m) != EOF&&n+m)
{
Init();
for(int i = 1; i <= n; i++)
{
scanf("%s",str+1);
for(int j = 1; j <= m; j++)
{
if(str[j] == '*') mp[i][j] = -1;
else mp[i][j] = str[j]-'A'+1,num[str[j]-'A'+1]++;
}
}
sum = num[1]+num[2]+num[3]+num[4];
if(num[1]%2||num[2]%2||num[3]%2||num[4]%2)//有的牌只有奇数个,无解
{
printf("no\n");
continue;
}
dfs(sum);
if(flag) printf("yes\n");
else printf("no\n");
}
}