您的位置:首页 > 其它

蓝桥杯 剪格子(dfs)

2018-03-19 00:15 281 查看
解题思路:dfs

AC代码如下:#include<stdio.h>
#include<string.h>

int image[20][20],n,m,nex[4][2]={0,1,1,0,0,-1,-1,0},s,cnt,book[20][20];

bool judge(int x,int y)
{
if(x<1||x>n||y<1||y>m)
return true;
return false;
}

void dfs(int x,int y,int sum,int step)
{
if(sum>s)
return ;
if(sum==s)
{
if(cnt>step)
cnt=step;
return ;
}
int i,nx,ny;
for(i=0;i<4;i++)
{
nx=x+nex[i][0];
ny=y+nex[i][1];
if(judge(nx,ny) || book[nx][ny])
continue;
book[nx][ny]=1;
dfs(nx,ny,sum+image[nx][ny],step+1);
book[nx][ny]=0;
}
return ;
}

int main()
{
int i,j;
scanf("%d%d",&m,&n);
s=0;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
scanf("%d",&image[i][j]);
s+=image[i][j];
}
if(s%2==0)
{
cnt=1010;
memset(book,0,sizeof(book));
s/=2;
book[1][1]=1;
dfs(1,1,image[1][1],1);
printf("%d\n",cnt);
}
else
printf("0\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: