您的位置:首页 > 其它

The problem of maze(经典迷宫问题) DFS版

2012-03-12 17:49 453 查看
又是这个题,上学期看过,但当时没能力自己写下来,只是把别人的代码认真的看了一遍。今天,终于自己把它给弄出来了。嘿嘿,经过自己思考的才能真正成为自己的东西。把这题做出来,可以说把DFS最基本的东西理解了。还应该学会灵活应用,那就得看日后的多多练习了。加油。

题目大意:输入一个h*w的矩阵,1表示blocks,0表示空白,2表示起点,3表示出口。寻找各种可以出来的方法。

simple input:

4 4
1201
1100
3010
1000
0 0

simple ouput:



#include <iostream>
#include <cstdio>
#include <fstream>
#include <memory.h>

#define MAX 10
using namespace std;

int dir[4][2]={0,1,-1,0,0,-1,1,0};
int map[MAX][MAX];
char s[10];
int w,h;
int start[2],end[2];
int flag;

struct node{
int x,y,fa;
node(int x1,int y1,int fa1)
{
x=x1;y=y1;fa=fa1;
}
node(){}
}nn[100];

void getmap(){
for(int i=0; i<h ; i++)
{
scanf("%s",s);
getchar();
for(int j=0 ; j<w ;j++)
{
map[i][j]=s[j]-'0';
if(map[i][j]==2)
{
start[0]=i;
start[1]=j;
map[i][j]=1;
}
if(map[i][j]==3)
{
end[0]=i;
end[1]=j;
}
}
}
}

void printmap(int k)
{
if(k==0) return;
else
{
printmap(nn[k].fa);
printf("(%d,%d,%d) ",nn[k].x,nn[k].y,nn[k].fa+1);
}
}

void dfs(int x,int y,int step)
{
int sx,sy;
if(x==end[0] && y==end[1])
{
flag=1;
nn[step+1]=node(x,y,step);
printmap(step);
printf("\n");
return;
}
for(int i=0; i<4; i++)
{
sx=x+dir[i][0];
sy=y+dir[i][1];
if(map[sx][sy]!=1 && sx>=0 && sx<h && sy>=0 && sy<w)
{
nn[step+1]=node(sx,sy,step);
map[sx][sy]=1;
dfs(sx,sy,step+1);
map[sx][sy]=0;
}
}
}
int main()
{
freopen("acm.txt","r",stdin);
while(scanf("%d%d",&h,&w)!=EOF && (w+h))
{
flag=0;
getmap();
nn[1]=node(start[0],start[1],0);
dfs(start[0],start[1],1);
if(!flag)
{
printf("Impossible!\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: