**
实验2-1迷宫问题
**
题目:一个5*5的迷宫,0代表可以走,1代表不可以走,从左上角走到右下角,已知有唯一的最短路径,打印出经过的路径
分析:这个题是典型的广度搜索问题,我理解错了题意,并不是路径是唯一的,而是最短的路径是唯一的,这样的话BFS有其天然优势,因为一层一层去搜,一旦知道肯定就是最短的。开始用DFS也是没考虑清这一点。
/*
*
*
* Created by haofeng on 3/3/20.
*此题尝试使用DFS来做,BFS同b题一样
*这个题不适合用DFS,原因是求最短路径,我理解错了题目,不是路径是唯一的,而是最短路径是唯一的,也就是说路径可能有多条
* 所以BFS是一层层搜的,本身就可以确保找到的是最短路径,DFS是深度优先搜索,想要求最短更复杂
*/
#include<iostream>
#include "stack"
#include <queue>
using namespace std;
struct node{
int x;
int y;
int preid;
int step;
};
int visit[5][5];
int MAZE[5][5];
int nextmove[4][2]={
{
0,1},{
0,-1},{
1,0},{
-1,0}};//down,up,right,left
int totalstep=0;
int totalid=0;
node thepath[20];
queue<node> nodequeue;
int step=0;
bool can_reach(int x,int y){
return MAZE[x][y]==0;
//judge if can reach
}
bool in_maze(int x,int y){
return 0<=x&&x<5&&0<=y&&y<5;
//judge if (x,y)in the maze
}
bool never_visit(int x,int y){
return visit[x][y]==0;
//return if it visited
}
void BFS(int x,int y){
int head=0;
int end=1;
node now_node;now_node.preid=now_node.x=now_node.y=now_node.step=0;
nodequeue.push(now_node);
while(!nodequeue.empty()){
thepath[head]=nodequeue.front();
now_node=nodequeue.front();
head++;
nodequeue.pop()