洛谷链接:https://www.luogu.com.cn/problem/P1649
错点:退出时机的选择
若是从1点开始选,那么选到第9个点选完之后下一次进入的时候就是第10步,那么应该是在11步的时候return
因为在走完第9步之后是有可能得到答案的,若是我们在第10步进行判断的话
所以一定要注意!!!
//需要搜索的次数会比较少
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1010;
int map[110];
int e[N],h[N],ne[N],idx;
int st[110];
int minn = 0x3f3f3f3f;
int get_num(int x,int y)
{
return 3*(x-1)+y;
}
void add(int a,int b)
{
e[idx] = b,ne[idx] = h[a],h[a] = idx++;
}
bool check()
{
for(int i=1;i<=9;i++) if(!map[i]) return 0;
return 1;
}
int fill(int u)
{
map[u] = !map[u];
for(int i=h[u];~i;i=ne[i])
{
int j = e[i];
map[j] = !map[j];
}
}
void dfs(int step,int sum)
{
if(sum>minn || step>10) return;
if(check())
{
minn = min(sum,minn);
return;
}
dfs(step+1,sum);
if(!st[step])
{
fill(step);
dfs(step+1,sum+1);
fill(step);
}
}
int main()
{
memset(h,-1,sizeof h);
for(int i=1;i<=3;i++)
for(int j=1;j<=3;j++)
cin>>map[get_num(i,j)];
add(1,2),add(1,4);
add(2,1),add(2,3),add(2,5);
add(3,2),add(3,6);
add(4,1),add(4,7),add(4,5);
add(5,2),add(5,4),add(5,6),add(5,8);
add(6,3),add(6,9),add(6,5);
add(7,4),add(7,8);
add(8,5),add(8,7),add(8,9);
add(9,6),add(9,8);
dfs(1,0);
cout<<minn<<endl;
return 0;
}
要加油哇!!!