【POJ】3009

来源:互联网 发布:知乎名字由来 编辑:程序博客网 时间:2024/06/06 13:58

http://poj.org/problem?id=3009

扔石头,上下左右四个方向如果某一个方向紧挨着block就不能扔这个方向,否则碰到block停住,block消失,再次四个方向扔。

注意剪枝。

#include <iostream>#include <cstring> using namespace std;const int maxn=35;int dx[4]={0,0,1,-1};int dy[4]={1,-1,0,0};int n,m;int sx,sy;int G[maxn][maxn];int ans;void dfs(int x,int y,int step){    if (step>=10||step>ans){        return;    }    for (int i=0;i<4;i++){        int xx=x+dx[i];        int yy=y+dy[i];        while (xx>=0&&xx<n&&yy>=0&&yy<m){            if (G[xx][yy]==0){                xx+=dx[i];                yy+=dy[i];            }            else            if (G[xx][yy]==1){                if (!(xx-dx[i]==x&&yy-dy[i]==y)){                    G[xx][yy]=0;                    dfs(xx-dx[i],yy-dy[i],step+1);                    G[xx][yy]=1;                }                xx=-1;            }            else            if (G[xx][yy]==3){                if (step+1<ans){                    ans=step+1;                }                xx=-1;            }        }    }}int main(){    while (cin >> m >> n){        if (m==0&&n==0) break;        for (int i=0;i<n;i++){            for (int j=0;j<m;j++){                cin >> G[i][j];            }        }        for (int i=0;i<n;i++){            for (int j=0;j<m;j++){                if (G[i][j]==2){                    sx=i;                    sy=j;                    i=n;                    break;                }            }        }        G[sx][sy]=0;        ans=11;        dfs(sx,sy,0);        if (ans>10){            cout << "-1" << endl;        }        else{            cout << ans << endl;        }    }}