题意:消灭星星= =,
解法:由于每次会减少一些,故不需要判重,全部转移的状态入队,直接暴力模拟操作
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<queue>
#include<set>
#include<stack>
#define cl(a,b) memset(a,b,sizeof(a));
#define LL long long
#define P pair<int,int>
#define X first
#define Y second
#define pb push_back
#define out(x) cout<<x<<endl;
using namespace std;
const int maxn=6;
const int inf=9999999;
const int mod=100007;
int n,m;
int a[maxn][maxn];
LL encode(int tu[][6]){///对图编码
LL code=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
code+=tu[i][j]*(1LL<<(i*6+j));
}
}
return code;
}
int dir[][2]={1,0,0,1,-1,0,0,-1};
bool vis[maxn][maxn];
int dfs_a[maxn][maxn];
void dfs(int x,int y,int color){///查找color连通块并相除
if(vis[x][y]||dfs_a[x][y]!=color)return ;
vis[x][y]=true;
dfs_a[x][y]=0;
for(int i=0;i<4;i++){
int xx=x+dir[i][0];
int yy=y+dir[i][1];
if(xx<0||xx>=n||yy<0||yy>=m)continue;
dfs(xx,yy,color);
}
}
int work_a[maxn][maxn];
void work(){///查找空白行并移动覆盖
for(int t=0;t<10;t++)
for(int i=1;i<n;i++){///行检查空行
for(int j=0;j<m;j++){
if(work_a[i][j]==0&&work_a[i-1][j]!=0){
work_a[i][j]=work_a[i-1][j];
work_a[i-1][j]=0;
}
}
}
for(int t=0;t<10;t++)
for(int j=0;j<m;j++){///查找空白列
bool ok=true;
for(int i=0;i<n;i++){
if(work_a[i][j]!=0){
ok=false;
break;
}
}
if(ok){
for(int col=j;col<m-1;col++){///左移空白列
for(int i=0;i<n;i++){
work_a[i][col]=work_a[i][col+1];
work_a[i][col+1]=0;
}
}
}
}
}
struct node{
int a[maxn][maxn];
int step;
node(){
step=0;
cl(a,0);
}
};
int bfs(){///广搜最短路
queue<node> q;
node tmp;
memcpy(tmp.a,a,sizeof(a));
tmp.step=0;
q.push(tmp);
while(!q.empty()){
node s=q.front();q.pop();
if(encode(s.a)==0)return s.step;
for(int k=1;k<=4;k++){
node x=s;
cl(vis,0);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++)if(s.a[i][j]==k&&!vis[i][j]){
memcpy(dfs_a,s.a,sizeof(s.a));
dfs(i,j,k);
memcpy(work_a,dfs_a,sizeof(dfs_a));
work();
LL tt=encode(work_a);
if(tt==0LL)return s.step+1;
memcpy(x.a,work_a,sizeof(work_a));
x.step=s.step+1;
q.push(x);
}
}
}
}
}
int main(){
while(~scanf("%d%d",&n,&m)){
cl(a,0);
cl(dfs_a,0);
cl(work_a,0);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%d",&a[i][j]);
}
}
printf("%d\n",bfs());
}
return 0;
}
/*
4 5
1 0 0 2 3
2 0 0 4 1
3 0 0 4 3
4 0 0 1 2
*/
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-08-11 21:58:16