深度优先搜索(deep first search)

来源:互联网 发布:提花组织软件 编辑:程序博客网 时间:2024/06/07 01:04

       深度优先搜索是一种在开发爬虫早期使用较多的方法。它的目的是要达到被搜索结构的叶结点(即那些不包含任何超链HTML文件) 。在一个HTML文件中,当一个超链被选择后,被链接的HTML文件将执行深度优先搜索,即在搜索其余的超链结果之前必须先完整地搜索单独的一条链。深度优先搜索沿着HTML文件上的超链走到不能再深入为止,然后返回到某一个HTML文件,再继续选择该HTML文件中的其他超链。当不再有其他超链可选择时,说明搜索已经结束。

      深度搜索应用的方面有很多,八皇后问题:

http://blog.csdn.net/q623702748/article/details/51108818

      在图方面的应用,深度搜索的思路就是按一定顺序向四周搜索,如果碰壁了就回溯。但是深度搜索找出的路径不一定是最优的,而且深度搜索带来的时间代价是不确定的,是根据你遍历的顺序决定的,如果图特别大,如果方向找错了,从起点到终点的代价是非常大的。

代码如下:

#define  _CRT_SECURE_NO_WARNINGS #include <iostream>using namespace std;/************************************************************************//*                        深度优先搜索(dfs)                     *//************************************************************************/enum { ROW = 7, COL = 7 };struct Node{int x;int y;friend istream &operator>>(istream &in, Node &node){in >> node.x >> node.y;return in;}};int map[ROW][COL] = {{ 0, 0, 1, 0, 1, 0, 1 },{ 1, 0, 0, 1, 0, 0, 1 },{ 1, 0, 1, 0, 0, 1, 0 },{ 1, 0, 0, 1, 0, 0, 1 },{ 0, 0, 0, 1, 0, 0, 1 },{ 1, 0, 1, 0, 0, 0, 1 },{ 1, 0, 0, 0, 1, 0, 1 },};bool vis[ROW][COL] = { 0 };int dir[4][2] = {{ -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 }};bool dfs(Node cur, Node dest){if (cur.x == dest.x && cur.y == dest.y) return true;int dir_x = cur.x;int dir_y = cur.y;if (map[dir_x][dir_y] != 1)//不在障碍物上面{for (int i = 0; i < 4; i++){int new_x = dir_x + dir[i][0];int new_y = dir_y + dir[i][1];//新产生的坐标是否已经在上一轮被访问过,或者该点是否为障碍物if (new_x >= 0 && new_y >= 0 && new_x < ROW&&new_y < COL && !vis[new_x][new_y] && !map[new_x][new_y]){Node n_cur = { new_x, new_y };vis[new_x][new_y] = true;//表示已经被访问if (dfs(n_cur, dest)){map[new_x][new_y] = 2;//若找到,则将路径标出,记号为2return true;}vis[new_x][new_y] = false;//取消标记,否则会影响下一轮操作}}}return false;//返回false,继续遍历}void init(){memset(vis, 0, sizeof(vis));for (int i = 0; i < ROW;i++)for (int j = 0; j < COL; j++){if (map[i][j] == 2)map[i][j] = 0;}}void print_map(){for (int i = 0; i < ROW; i++){for (int j = 0; j < COL; j++)std::cout << map[i][j] << " ";std::cout << std::endl;}}int main(void){Node cur = { 0, 0 };Node dest = { 3, 1 };print_map();while (cin >> cur >> dest){init();if (map[cur.x][cur.y] != 1 && map[dest.x][dest.y] != 1){map[cur.x][cur.y] = 2;if (dfs(cur, dest)){std::cout << "找到了" << std::endl;}else{std::cout << "找不到" << std::endl;}}print_map();system("pause");system("cls");init();print_map();}cout << endl;system("pause");return 0;}




1 0
原创粉丝点击