您的位置:首页 > 其它

挑战程序设计竞赛里面的几道深度优先搜索

2014-04-02 20:25 411 查看
poj2386 Lake Counting 简单题

/*
ID: neverchanje
PROG:
LANG: C++11
*/
#include<vector>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<set>
#include<queue>
using namespace std;

int w,h;
int map[21][21];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int sx,sy,ML;
bool vis[21][21];

bool border(int x,int y){
return (x>=h || x<0 || y<0 ||y>=w);
}

void dfs(int x,int y,int mve){
if(mve>10||mve>ML)//如果已经超出预期,则不可到达
return;
for(int i=0;i<4;i++){
int nx=x+dir[i][0];int ny=y+dir[i][1];
if( border(nx,ny) || map[nx][ny]==1 )
continue;//////////////
while(1){
if(border(nx,ny))
break;
if(!map[nx][ny]){
nx+=dir[i][0];ny+=dir[i][1];
continue;
}

if(map[nx][ny]==1)
{
map[nx][ny]=0;
dfs(nx-dir[i][0],ny-dir[i][1],mve+1);
map[nx][ny]=1;
break;
}

if(map[nx][ny]==3)
{
ML=min(ML,mve+1);
return;
}
}
}
}

int main(){
//    freopen("a.txt","r",stdin);
//    freopen(".out","w",stdout);
while(cin>>w>>h){
if(!(w|h))    break;

memset(map,0,sizeof(map));
for(int i=0;i<h;i++)
for(int j=0;j<w;j++){
scanf("%d",&map[i][j]);
if(map[i][j]==2){
sx=i;sy=j;
}
}

ML=11;///
map[sx][sy]=0;
dfs(sx,sy,0);
if(    ML<=10)
cout<<ML<<endl;
else
cout<<-1<<endl;
}
return 0;
}

/*
DESCRIPTION:
快被这题整哭了。。。。以后不敢再随便设公有变量了FUCK!!!
*/


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: