c++实现深度优先搜索(DFS)
2018-03-09 16:00 天马流星1993 阅读(4856) 评论(0) 编辑 收藏 举报注明:原文见博客http://blog.csdn.net/raphealguo/article/details/7560918,写的非常详细、细致。
我主要针对它的算法实现了C++版本的深度度优先搜索。
迷宫问题(略作修改):
定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 1, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出是否有指定长度的路线。
代码:
#include<math.h>
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
#include<queue>
#define MAXL 5
using namespace std;
bool isValid(vector<vector<int> >& maze, int x, int y){
return !maze[x][y];
}
bool maze_search(vector<vector<int> >& maze, bool (*visit)[MAXL], vector<int>& vs, int d, int goal){
if (d == goal)
return true;
int dir[][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
for (int i = 0; i<4; i++){
vector<int> vn;
int vx = vs[0] + dir[i][0];
int vy = vs[1] + dir[i][1];
vn.push_back(vx);
vn.push_back(vy);
if ((vx >= 0 && vx<MAXL && vy >= 0 && vy<MAXL) && isValid(maze, vx, vy) && !visit[vx][vy]){
visit[vx][vy] = true;
if (maze_search(maze, visit, vn, d + 1, goal)){
cout << "(" << vx << "," << vy << ")" << " ";
return true;
}
visit[vx][vy] = false;
}
}
return false;
}
void display_2_vector(vector<vector<int> >& ivec){
for (int i = 0; i<ivec.size(); i++){
for (int j = 0; j<ivec[0].size(); j++){
cout << ivec[i][j] << " ";
}
cout << endl;
}
}
int main(void)
{
int a[MAXL][MAXL] = { { 0, 1, 0, 0, 0 }, { 0, 1, 0, 1, 0 }, { 0, 0, 0, 1, 0 }, { 0, 1, 1, 1, 0 }, { 0, 0, 0, 1, 0 } };
vector<vector<int> > maze(MAXL, vector<int>(MAXL));
for (int i = 0; i<MAXL; i++){
for (int j = 0; j<MAXL; j++){
maze[i][j] = a[i][j];
}
}
vector<int> vs(2, 0);
int goal = 12;
int d = 0;
bool visit[MAXL][MAXL] = { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, {0,0,0,0,0} };
visit[0][0] = 1;
cout << maze_search(maze, visit, vs, d, goal) << endl;
display_2_vector(maze);
}