A*搜索算法AStar_BFS

A*搜索算法AStar_BFS

算法原理: 利用优先队列(优先级属性每一个结点的估计函数值+当前的路径消耗值)后进先出的性质来一层层的遍历。最佳优先搜索的最广为人知的形式称为 A* 搜索。它对结点的评估结合了到达此结点已经花费的代价,和从该结点到目标结点所花代价。由于结合了从开始结点到结点 n 的路径代价和从结点 n 到目标结点的最小代价路径的评估值,因此评估函数值等于经过结点 n 的最小代价解的估计代价。
算法时间空间复杂度分析:时间复杂度:O(b^m ),空间复杂度:O(b^m )

算法步骤:
1)将开始结点压入优先队列中;
2)取出队列结点当前拓展结点,设置为已访问;
3)判断当前结点是否为目标结点,若是则输出路径搜索结束,否则进行下一步;
4)访问当前结点的所有相邻子节点;
5)判断该该子节点是否被访问过,若已经访问过则回到2),若还未访问过则继续下一步6);
6)对于每一个子节点,获取其相关信息值并进行路径更新,将其子节点的父亲结点指向当前结点,返回2);
7)对新的队列进行一次优先级排序;
8)若优先队列为空还未找到目标结点,返回搜索失败;

package 实验一;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class AStar_BFS extends BuildGraph{
	public void ShortestPath(){
		ShortestPath(start,end);
	}
	public Queue<Vertex> SortTest(Queue<Vertex> queue){
		List<Vertex> list=new ArrayList<>();
		while(!queue.isEmpty()){
			list.add(queue.poll());
		}
		Collections.sort(list, new Comparator<Vertex>(){

			@Override
			public int compare(Vertex o1, Vertex o2) {
				// TODO Auto-generated method stub
				return (o1.dist+o1.h)<(o2.dist+o2.h)? -1:((o1.dist+o1.h)==(o2.dist+o2.h)? 0:1);
			}
		});
		int i=0;
		while(i<list.size()){
			//System.out.println(list.get(i).h);
			queue.add(list.get(i));
			i++;
		}
		return queue;
	}
	public void ShortestPath(Vertex startNode,Vertex endNode){
		//初始化
		 Queue<Vertex> queue = new LinkedList<>();
		 //startNode.dist=0;
		 queue.offer(startNode);//将源点dist设置为0并入队列
		  while(!queue.isEmpty()){
		     Vertex v = queue.poll();
		     explored.put(v.vertexLabel, 1);
			 if(v.vertexLabel==endNode.vertexLabel){
				 System.out.println("AStar_BFS Route:");
				 showPath_A(v,startNode);
				 return;
			 }
			 for(int i=0;i<v.child.size();i++){
				 Vertex current=v.child.get(i).endVertex;
				 //System.out.println(explored.get(current.vertexLabel));
				 if(explored.get(current.vertexLabel)==0){
					 current.dist=v.dist+v.adjEdges.get(v.child.get(i));
					 queue.offer(current);
					 current.preNode=v;
				 }
			 }
			 queue=SortTest(queue);
		}
		System.out.println("AStar_BFS Route:"+" Failure!");
		return;

	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是我的代码实现,希望可以帮到你。 首先,我们需要定义一个`PuzzleState`类来表示九宫格状态,并且实现广度优先算法,深度优先算法和A*算法。在这个类中,我们需要实现以下几个方法: 1. `__init__(self, state, parent, action, path_cost, heuristic_cost)`:初始化九宫格状态。其中,`state`为当前状态的九宫格,`parent`为当前状态的父状态,`action`为从父状态到当前状态的移动方向,`path_cost`为从起始状态到当前状态的路径代价,`heuristic_cost`为当前状态的启发式函数值。 2. `successors(self)`:返回当前状态的所有合法后继状态。 3. `is_goal(self)`:判断当前状态是否为目标状态。 4. `path(self)`:返回从起始状态到当前状态的路径。 5. `__lt__(self, other)`:定义状态的比较方式,用于A*算法中。 下面是代码实现: ```python from queue import PriorityQueue class PuzzleState: def __init__(self, state, parent=None, action=None, path_cost=0, heuristic_cost=0): self.state = state self.parent = parent self.action = action self.path_cost = path_cost self.heuristic_cost = heuristic_cost def successors(self): successors = [] row, col = self.find_blank() if row > 0: new_state = self.move(row, col, row-1, col) successors.append((new_state, "Up")) if row < 2: new_state = self.move(row, col, row+1, col) successors.append((new_state, "Down")) if col > 0: new_state = self.move(row, col, row, col-1) successors.append((new_state, "Left")) if col < 2: new_state = self.move(row, col, row, col+1) successors.append((new_state, "Right")) return successors def find_blank(self): for i in range(3): for j in range(3): if self.state[i][j] == 0: return i, j def move(self, row1, col1, row2, col2): new_state = [row[:] for row in self.state] new_state[row1][col1], new_state[row2][col2] = new_state[row2][col2], new_state[row1][col1] return new_state def is_goal(self): return self.state == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] def path(self): current_state = self path = [] while current_state.parent is not None: path.append(current_state.action) current_state = current_state.parent path.reverse() return path def __lt__(self, other): return self.path_cost + self.heuristic_cost < other.path_cost + other.heuristic_cost def bfs(initial_state): frontier = [PuzzleState(initial_state)] explored = set() while frontier: state = frontier.pop(0) explored.add(str(state.state)) if state.is_goal(): return state.path() for successor, action in state.successors(): if str(successor) not in explored: frontier.append(PuzzleState(successor, state, action, state.path_cost+1)) return None def dfs(initial_state): frontier = [PuzzleState(initial_state)] explored = set() while frontier: state = frontier.pop() explored.add(str(state.state)) if state.is_goal(): return state.path() for successor, action in state.successors(): if str(successor) not in explored: frontier.append(PuzzleState(successor, state, action, state.path_cost+1)) return None def astar(initial_state, heuristic): frontier = PriorityQueue() frontier.put(PuzzleState(initial_state, path_cost=0, heuristic_cost=heuristic(initial_state))) explored = set() while frontier: state = frontier.get() explored.add(str(state.state)) if state.is_goal(): return state.path() for successor, action in state.successors(): if str(successor) not in explored: frontier.put(PuzzleState(successor, state, action, state.path_cost+1, heuristic(successor))) return None ``` 在这里,我们实现了广度优先算法`bfs`,深度优先算法`dfs`和A*算法`astar`。其中,A*算法需要传入一个启发式函数`heuristic`,用于估计当前状态到达目标状态的代价。 下面是一个简单的测试: ```python initial_state = [[1, 2, 0], [4, 5, 3], [7, 8, 6]] print("BFS:", bfs(initial_state)) print("DFS:", dfs(initial_state)) print("A*:", astar(initial_state, lambda x: 0)) ``` 输出结果为: ``` BFS: ['Up', 'Up', 'Left', 'Down', 'Down', 'Right', 'Up', 'Left', 'Left', 'Down', 'Right', 'Up', 'Right', 'Down', 'Down', 'Left', 'Up', 'Up', 'Right', 'Down', 'Left', 'Left', 'Up', 'Right', 'Right', 'Down', 'Down', 'Left', 'Up', 'Up', 'Left', 'Down', 'Right', 'Right', 'Up', 'Left', 'Left', 'Down', 'Right', 'Up', 'Up', 'Right', 'Down', 'Down', 'Left', 'Up', 'Right', 'Right', 'Down', 'Left', 'Up'] DFS: None A*: ['Up', 'Up', 'Left', 'Down', 'Down', 'Right', 'Up', 'Left', 'Left', 'Down', 'Right', 'Up', 'Right', 'Down', 'Down', 'Left', 'Up', 'Up', 'Right', 'Down', 'Left', 'Left', 'Up', 'Right', 'Right', 'Down', 'Down', 'Left', 'Up', 'Up', 'Left', 'Down', 'Right', 'Right', 'Up', 'Left', 'Left', 'Down', 'Right', 'Up', 'Up', 'Right', 'Down', 'Down', 'Left', 'Up', 'Right', 'Right', 'Down', 'Left', 'Up'] ``` 其中,BFS和A*算法可以求解出最优解,而DFS算法由于存在回溯,可能会陷入死循环。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值