
5 6 0 0 0 3 4 4 0 1 1 3 3 3 2 2 1 2 3 3 1 1 1 1 3 3 2 2 1 4 4 4
4Hint0 0 0 3 4 4 0 0 0 4 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 3 3 3 0 0 3 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 1 2 3 3 0 0 3 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 3 3 2 2 2 3 3 0 2 2 2 4 4 0 2 2 0 0 0 0 0 0 0 0 0 0 2 2 1 4 4 4 2 2 4 4 4 0 2 2 4 4 4 0 2 2 2 0 0 0 0 0 0 0 0 0
思路:因为方块会越消越少,所以没必要判重。注意消去之后,上面的会掉下来,如果某一列全为是空的,右边的会往左移。
#include <stdio.h>
struct{
int d[6][6],step;
}que[1000000],t;
int n,m,temp[6][6],nxt[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
bool vis[6][6];
void dfs(int x,int y,int num)
{
for(int i=0;i<4;i++)
{
x+=nxt[i][0];
y+=nxt[i][1];
if(x>=0 && x<n && y>=0 && y<m && !vis[x][y] && temp[x][y]==num)
{
vis[x][y]=1;
t.d[x][y]=0;
dfs(x,y,num);
}
x-=nxt[i][0];
y-=nxt[i][1];
}
}
int main()
{
int i,j,k,p,q,top,bottom;
bool flag;
while(~scanf("%d%d",&n,&m))
{
for(i=0;i<n;i++) for(j=0;j<m;j++) scanf("%d",&que[0].d[i][j]);
top=0;
bottom=1;
que[0].step=0;
while(top<bottom)
{
t=que[top];
flag=1;
for(i=0;i<n && flag;i++) for(j=0;j<m && flag;j++) if(t.d[i][j]) flag=0;
if(flag)
{
printf("%d\n",t.step);
break;
}
t.step++;
for(i=0;i<n;i++) for(j=0;j<m;j++) temp[i][j]=t.d[i][j],vis[i][j]=0;
for(i=0;i<n;i++) for(j=0;j<m;j++)
{
if(temp[i][j] && !vis[i][j])
{
vis[i][j]=1;
t.d[i][j]=0;
dfs(i,j,temp[i][j]);
for(p=n-1;p>=0;p--)//向下移动
{
for(q=0;q<m;q++)
{
if(!t.d[p][q])
{
for(k=p-1;k>=0;k--)
{
if(t.d[k][q])
{
t.d[p][q]=t.d[k][q];
t.d[k][q]=0;
break;
}
}
}
}
}
for(q=0;q<m-1;q++)//向左移动
{
for(p=0;p<n;p++) if(t.d[p][q]) break;
if(p<n) continue;
for(p=0;p<n;p++)
{
t.d[p][q]=t.d[p][q+1];
t.d[p][q+1]=0;
}
}
que[bottom++]=t;
for(p=0;p<n;p++) for(q=0;q<m;q++) t.d[p][q]=temp[p][q];
}
}
top++;
}
}
}
HDU-3295-An interesting mobile game(BFS),布布扣,bubuko.com
HDU-3295-An interesting mobile game(BFS)
原文:http://blog.csdn.net/faithdmc/article/details/38538613