// poj3009 Curling 2.0
// dfs水题,开始的时候没有想到在走了10步以后就不走了这个重要的剪枝,
// 结果tle了。。。
// 后来想了个vis数组记录走过的路径,结果发现并不能这样标记,因为每个点可能
// 走多次,所以这样是不对的
//
// 哎,继续练吧,水题都差不多搜了一个小时,哎,。。。
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define ceil(a,b) (((a)+(b)-1)/(b))
#define endl '\n'
#define gcd __gcd
#define highBit(x) (1ULL<<(63-__builtin_clzll(x)))
#define popCount __builtin_popcountll
typedef long long ll;
using namespace std;
const int MOD = 1000000007;
const long double PI = acos(-1.L);
template<class T> inline T lcm(const T& a, const T& b) { return a/gcd(a, b)*b; }
template<class T> inline T lowBit(const T& x) { return x&-x; }
template<class T> inline T maximize(T& a, const T& b) { return a=a<b?b:a; }
template<class T> inline T minimize(T& a, const T& b) { return a=a<b?a:b; }
const int maxn = 32;
int g[maxn][maxn];
int n,m;
int vis[maxn][maxn];
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
int t;
int mi;
int nowx,nowy;
const int inf = 0x3f3f3f3f;
void print(){
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
printf("%d ",g[i][j]);
}
puts("");
}
}
void init(){
mi = inf;
for (int i=0;i<n;i++)
for (int j=0;j<m;j++){
scanf("%d",&g[i][j]);
if (g[i][j]==3){
nowx = i;
nowy = j;
}
}
memset(vis,0,sizeof(vis));
}
void dfs(int x,int y,int cnt){
// print();
// puts("");
// vis[x][y] = 1;
if (cnt>10){ //题目有要求
return ;
}
if (x==nowx&&y==nowy){
mi = min(cnt,mi);
vis[x][y] = 0;
return ;
}
//vis[x][y] = 1;
for (int i=0;i<4;i++){
int tx = x + dx[i];
int ty = y + dy[i];
if (tx<0||tx>=n||ty<0||ty>=m) // 判断越界
continue;
if (g[tx][ty]==1) //冰壶需要隔一个才能推动
continue;
for (int k=1;k<=max(n,m);k++){
tx = x + dx[i] * k;
ty = y + dy[i] * k;
if (tx<0||tx>=n||ty<0||ty>=m)
continue;
if (g[tx][ty]==1){
// int t = g[tx][ty];
// vis[tx][ty] = 1;
g[tx][ty] = 0;
dfs(tx-dx[i],ty-dy[i],cnt+1);
g[tx][ty] = 1;
break;
}else if (g[tx][ty]==3){
dfs(tx,ty,cnt+1);
// break;
}
}
}
//vis[x][y] = 0;
}
void solve(){
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
if (g[i][j]==2)
dfs(i,j,0);
if (mi==inf)
mi = -1;
printf("%d\n",mi);
}
int main() {
//freopen("G:\\Code\\1.txt","r",stdin);
while(scanf("%d%d",&m,&n)!=EOF){
if (!m&&!n)
break;
init();
solve();
}
return 0;
}
poj 3009 Curling 2.0 dfs回溯
最新推荐文章于 2022-07-01 15:52:58 发布