繁体   English   中英

如何表示不加权有向图并找到最短路径? Java的

[英]How to represent a unweight directed graph and find the shortest path? Java

用Java表示图形的最佳方法是什么? 我这样做是这样的:

public class Node<T> {
public T data;
public LinkedList<Node> children;
public Node(T data) {
    this.data = data;
    this.children = new LinkedList<Node>(); //here there are the connected nodes of the node
}

public T getData() {
    return this.data;
}
public void addArch(Node n) {
    children.add(n);
}


public class Graph <T> {
private Node<T> source = new Node(null);
private Node<T> target = new Node(null);
private ArrayList<Node> nodes = new ArrayList<Node>();

public Graph() {}
public void addNode(T v) {
    boolean visto = false;
    for (Node n: nodes) {
        if (n.getData().equals(v)) {
            visto = true;
        }
    }
    if (visto == false) {
        nodes.add(new Node(v));
    }
}
public void addEdge(T p, T a) throws NoSuchNodeException {
    boolean visto = false;
    boolean visto_secondo = false;
    for (Node n: nodes) {
        if (n.getData().equals(p)) {
            visto = true;
        }
    }
    for (Node n: nodes) {
        if (n.getData().equals(a)) {
            visto_secondo = true;
        }
    }
    if (visto == false || visto_secondo == false) {
        throw new NoSuchNodeException();
    }
    else {
        for (Node n : nodes) {
            if (p.equals(n.getData())) {
                System.out.print(a);

                n.addArch(new Node(a));
            }
        }
    }

}

我必须找到最短的路径,但是好像没有添加拱门,为什么? 我也做了源和目标的设置和获取。 但是,我必须找到此源和目标之间的最短路径,使用什么算法? 我需要使用bfs来获得最短路径,但是我的问题是如何遍历拱门,我需要做一个递归函数

找到目标节点最短路径的最佳算法是迭代加深A *

如果启发式值是可接受的,它会找到到达目标节点的最短路径,这意味着它不会高估。

这是伪代码:

 node              current node
 g                 the cost to reach current node
 f                 estimated cost of the cheapest path (root..node..goal)
 h(node)           estimated cost of the cheapest path (node..goal)
 cost(node, succ)  step cost function
 is_goal(node)     goal test
 successors(node)  node expanding function, expand nodes ordered by g + h(node)

 procedure ida_star(root)
   bound := h(root)
   loop
     t := search(root, 0, bound)
     if t = FOUND then return bound
     if t = ∞ then return NOT_FOUND
     bound := t
   end loop
 end procedure

 function search(node, g, bound)
   f := g + h(node)
   if f > bound then return f
   if is_goal(node) then return FOUND
   min := ∞
   for succ in successors(node) do
     t := search(succ, g + cost(node, succ), bound)
     if t = FOUND then return FOUND
     if t < min then min := t
   end for
   return min
 end function

g表示达到当前状态的移动次数,h表示达到目标状态的估计移动次数。 f := g + h(node) 启发式值越接近实际移动次数,算法就越快

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM