迷宫问题 dfs bfs 搜索

时间:2023-03-09 09:24:21
迷宫问题 dfs bfs 搜索
定义一个二维数组:
int maze[5][5] = {

0, 1, 0, 0, 0,

0, 1, 0, 1, 0,

0, 0, 0, 0, 0,

0, 1, 1, 1, 0,

0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4) 这种找出路径并且输出,一般我们都只会用bfs,实际上dfs也是可以解决的
但是这样解题是有缺陷的,因为这个题目只有一条路,已经确定了,所以可以用dfs,若是求不止一条的最短路,就不行
dfs 方法可以学习一下
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std; int path[100][2],a[10][10],ans;
bool vis[10][10],flag=0;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0}; bool judge(int x,int y)
{
if(x>=0&&y>=0&&x<=4&&y<=4&&!flag&&!vis[x][y]&&!a[x][y]) return 1;
return 0;
} void dfs(int x,int y,int step)
{
path[step][0]=x;
path[step][1]=y;
if(x==4&&y==4)
{
flag=1;
ans=step;
return ;
}
for(int i=0;i<4;i++)
{
int tx=x+dx[i];
int ty=y+dy[i]; if(judge(tx,ty))
{
vis[tx][ty]=1;
dfs(tx,ty,step+1);
vis[tx][ty]=0;
}
}
}
int main()
{
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
scanf("%d",&a[i][j]);
}
}
dfs(0,0,1); for(int i=1;i<=ans;i++)
{
printf("(%d, %d)\n",path[i][0],path[i][1]);
}
return 0;
}

  

bfs 也挺好的,可以学习学习
#include<stdio.h>
#include<string.h>
#include<queue>
#include<vector>
using namespace std;
int t[4][2]={0,1,1,0,-1,0,0,-1};
typedef pair<int,int> ee;
int vis[10][10];
int a[10][10];
int d[10][10];
ee b[10][10];
ee exa;
void bfs()
{
int sx=0,sy=0;
int tx,ty;
memset(vis,0,sizeof(vis));
queue<ee>q;
q.push(ee(sx,sy));
vis[sx][sy]=true;
d[sx][sy]=0; while(!q.empty())
{
exa=q.front();q.pop();
if(exa.first==4&&exa.second==4) break; for(int i=0;i<4;i++)
{
tx=exa.first+t[i][0];
ty=exa.second+t[i][1]; if(ty<0||tx<0||ty>5||tx>5) continue;
if(vis[tx][ty]) continue;
if(a[tx][ty]==1) continue; vis[tx][ty]=true;
d[tx][ty]=d[exa.first][exa.second]+1;
b[tx][ty]=exa;
q.push(ee(tx,ty));
}
}
return;
}
void print()
{
vector<ee> node;
while(1)
{
node.push_back(exa);
if(d[exa.first][exa.second]==0) break;
exa=b[exa.first][exa.second];
}
// node.push_back(ee(sx,sy)); for(int i=node.size()-1;i>=0;i--)
{
printf("(%d, %d)\n",node[i].first,node[i].second);
}
} int main()
{
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
scanf("%d",&a[i][j]);
}
}
bfs();
print();
return 0;
}