利用广度优先搜索来解决最短路径问题

今天写的内容是在CSDN看到一些有关于优先搜索讲解的文章,然后有一些理解。

广度优先搜索和深度优先搜索就是图的遍历,那什么叫做图的遍历呢,从图的某个顶点出发,沿图中的路径依次访问图中所有顶点,并且使得图中所有顶点都恰好被访问一次,这一过程即为图的遍历。需要注意的是,接下来讨论图的遍历时,都是特指在一个连通图上进行遍历。

图有最两种常见的遍历方法,就是广度优先搜索和深度优先搜索。

简单来说广度优先搜索就是一层一层地往下走,而深度优先搜索则是照着一条路径一个劲儿的往下走(就像是不撞南墙不回头)。

而在解决最短路径的问题时,像迷宫这种类型的问题时,就可以很好的利用BFS来解决。

迷宫问题原题目

https://blog.csdn.net/C20190413/article/details/73103529

这代题目的代码就充分体现了广度优先搜索的内容。

代码


#include<cstdio>

#include<cstring>

int head=0,tail=1,nextx,nexty;

int pre[100000],a[100000],b[100000];

int x[4]={0,0,1,-1},y[4]={1,-1,0,0};

bool mark[5][5];

int map[5][5];

int wayx[25],wayy[25];

void find(int d)

{

    if(pre[d]!=0){find(pre[d]);printf("(%d, %d)\n",wayx[d],wayy[d]);}

}

bool check(int x,int y)

{

    if(x<5&&y<5&&x>=0&&y>=0)return 1;

    return 0;

}

void bfs()

{

    a[1]=0;

    b[1]=0;

    mark[0][0]=1;

    pre[1]=0;

    head=0;tail=1;

    while(head!=tail)

	{

		head++;

		for(int i=0;i<4;i++)

		{

			nextx=a[head]+x[i];

			nexty=b[head]+y[i]; 

			if(check(nextx,nexty)&&!mark[nextx][nexty]&&map[nextx][nexty]==0)

			{

				tail++;

				a[tail]=nextx;

                b[tail]=nexty;

				pre[tail]=head;

				wayx[tail]=nextx;

				wayy[tail]=nexty;

				mark[nextx][nexty]=1; 

				if(a[tail]==4&&b[tail]==4)

				{

					printf("(0, 0)\n");

					find(tail);

					return ;

				}

			}

		}

	}

}

main()

{

	for(int i=0;i<5;i++)

		for(int j=0;j<5;j++)

			scanf("%d",&map[i][j]);

	bfs();

}

 

好的,针对你的问题,我可以给出以下的 Python 代码实现: ``` from collections import deque # 定义有向图的邻接表表示 graph = { 'A': {'B': 1, 'C': 4}, 'B': {'D': 2}, 'C': {'D': 1}, 'D': {'E': 3}, 'E': {} } # 定义广度优先算法求最短路径 def bfs_shortest_path(graph, start, end): queue = deque([(start, [start])]) # 使用双向队列,初始化为起点 visited = set() # 记录已访问的节点 while queue: node, path = queue.popleft() # 取出队列中的节点和路径 if node not in visited: # 如果节点没有被访问过 visited.add(node) # 标记为已访问 if node == end: # 如果找到了终点 return path # 返回路径 for neighbor, weight in graph[node].items(): # 遍历邻居节点 if neighbor not in visited: # 如果邻居节点没有被访问过 queue.append((neighbor, path + [neighbor])) # 将邻居节点加入队列,并记录路径 return None # 如果没有找到路径,返回 None # 测试代码 start = 'A' end = 'E' shortest_path = bfs_shortest_path(graph, start, end) if shortest_path: print(f"The shortest path from {start} to {end} is: {' -> '.join(shortest_path)}") else: print(f"There is no path from {start} to {end}") ``` 在这个例子中,我们定义了一个有向图的邻接表表示,使用 `deque` 实现双向队列,并采用广度优先搜索算法来搜索最短路径。最后,我们利用测试代码对算法进行测试,输出最短路径结果。 希望这个例子能够帮助你理解如何利用广度优先算法找出最短路径
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值