我有以下代码,它们正在使用DFS寻找最短的路线,并且正在寻找一种方法来找到最短的路线,但是使用UCS搜索算法。
我尝试通过以下代码进行更改:
Uniform-cost-search(problem)
OPEN ← ( make-node(problem[init-state], NIL, 0) )
CLOSE ← NIL
while open ≠ ( ) do
next ← pop(OPEN)
CLOSE ← CLOSE ∪ {next}
if problem[goal-test](next) then
return(path(new))
loop for s in expand(next[state])
if not(find-state(s, CLOSE) then
new-cost ← next[g]+cost(next[state], s)
old-node ← find-state(s, OPEN)
if old-node then
if old-node[g] > new-cost then
old-node[g] ← new-cost
old-node[parent] ← next
; Insert an item into a sorted list according to field g
insert(old - node, OPEN - {old-node}, g)
else ; no node with same state in open
new ← make-node(s, next, new-cost)
insert(new, OPEN, g)
return(FAIL) ; OPEN is empty - no solution
我尝试使用队列优先级来相应地更改代码,但并非如此。
我的代码:
public LinkedList shortestPath(int src, int dest) {
Stack<Integer> stack = new Stack<Integer>();
LinkedList<Integer> result = new LinkedList<Integer>();
int prev[] = new int[numOfVertices];
if (src == dest)
return result;
stack.add(src);
for (int i = 0; i < numOfVertices; i++) {
prev[i] = -1;
}
while (!stack.empty()) {
int current = stack.pop();
Iterator<Integer> i = adjacency[current].listIterator();
while (i.hasNext()) {
int n = i.next();
if (prev[n] == -1) {
prev[n] = current;
// we reached to destination
// build the result list
if (n == dest) {
while (n != src) {
result.addFirst(n);
n = prev[n];
}
// add src to result list
result.addFirst(src);
return result;
}
stack.add(n);
}
}
}
return result;
}
使用UCS查找最短路线。
谢谢。