题目:棋盘
思路:
搜索+剪枝。
55分:裸的dfs,传4个参:横纵坐标,当前的步数,走到当前步是否使用魔法。
60分:加一个最优性剪枝,判断当前步数大于等于ans时可直接回溯。
100分:再加一个最优性剪枝,类似于记忆化。定义状态f[x][y][t]表示横纵坐标为x,y,颜色为t时的最小步数。当前步数大于等于f[x][y][t]时也可以直接回溯。
注意一定不要瞎用bool类型!把int写成bool自然溢出不会报错好难调……错了几次了。
代码:
#include<bits/stdc++.h>
using namespace std;
#define maxn 100
#define read(x) scanf("%d",&x)
const int m1[5]={0,1,-1,0,0};
const int m2[5]={0,0,0,1,-1};
int n,m;
int a[maxn+5][maxn+5];
int ans=1e9;
bool vis[maxn+5][maxn+5];
int f[maxn+5][maxn+5][4];
void dfs(int x,int y,int stp,bool c) {
if(stp>=ans) return ;
if(f[x][y][a[x][y]]&&stp>=f[x][y][a[x][y]]) return ;
f[x][y][a[x][y]]=stp;
if(x==n&&y==n) {
ans=min(ans,stp);
return ;
}
vis[x][y]=true;
for(int i=1;i<=4;i++) {
int h1=x+m1[i],h2=y+m2[i];
if(h1<=0||h2<=0||h1>n||h2>n) continue;
if(vis[h1][h2]) continue;
if(a[h1][h2]) {
if(a[h1][h2]==a[x][y]) dfs(h1,h2,stp,0);
else dfs(h1,h2,stp+1,0);
} else if(!c) {
a[h1][h2]=a[x][y];
dfs(h1,h2,stp+2,1);
a[h1][h2]=0;
}
}
vis[x][y]=false;
}
int main() {
read(n),read(m);
for(int i=1;i<=m;i++) {
int x,y,z;
read(x),read(y),read(z);
if(z==0) z=2;
a[x][y]=z;
}
dfs(1,1,0,0);
printf("%d",ans==(1e9)?-1:ans);
return 0;
}