我目前正在处理一个Dijkstras算法问题,并打了一堵砖墙。我的任务是我在一个单层的建筑里,有X乘Y的房间。每间客房都需要付费。在边界上是几个出口,我必须找到从随机放置的起点到其中一个出口的最短路径。
在我解释我遇到的问题之前,我会解释一下我的一些代码。
我创建了一个名为room的类来存储每个成本和邻接:
static class room implements Comparable<room> {
int value;
int i;
int k;
PriorityQueue<room> adj = new PriorityQueue<room>();
double distance = Double.POSITIVE_INFINITY;
room(int i, int k, int v) {
this.k = k;
this.i = i;
this.value = v;
}
@Override
public int compareTo(room o) {
return this.value - o.value;
}
每个房间的邻近区域仅包括北,东,南和西的房间。
static void adjacent(room[][] field, int row, int column) {
for (int i = 1; i <= row; i++) {
for (int k = 1; k <= column; k++) {
if (field[i][k + 1] != null) {
field[i][k].adj.add(field[i][k + 1]);
}
if (field[i][k - 1] != null) {
field[i][k].adj.add(field[i][k - 1]);
}
if (field[i + 1][k] != null) {
field[i][k].adj.add(field[i + 1][k]);
}
if (field[i - 1][k] != null) {
field[i][k].adj.add(field[i - 1][k]);
}
}
}
我的变量start是我开始的第一个房间。我创建了一个方法,一次一个地轮询它的邻接并将它发送给这个方法。
static void closestExit(room s) {
while (s.adj.size() != 0) {
LinkedList<room> q = new LinkedList<>();
q.add(s.adj.poll());
q.peek().distance = q.peek().value;
while (q.size() != 0) {
if (q.peekLast().adj.size() == 0)//if adj list is empty then remove it from the list or if last in queue is an X remove it
{
backtrack(q);
} else if (q.peekLast().value == 'X') {
q.removeLast();
} else if (q.peekLast().adj.peek().value == 'X' || q.peekLast().adj.peek().value == 'S')//if head of adj list is S or X then it removes it
{
q.peekLast().adj.remove();
} else if (q.peekLast().distance > shortpath)//checks distance to see if it went over dpath.
{
backtrack(q);
} else if (checkExit(q.peekLast().adj))//if exit is in adj list then record the distance
{
shortpath = q.peekLast().distance;
backtrack(q);
} else {
if (!(q.contains(q.peekLast().adj.peek())))//checks to see if the list already has this room in it
{
q.peekLast().adj.peek().distance = q.peekLast().adj.peek().value + q.peekLast().distance;
q.add(q.peekLast().adj.poll());
} else {
q.peekLast().adj.remove();
}
}
}
}
if (shortpath == Double.POSITIVE_INFINITY) {
shortpath = -1;
}
}
正在发生的问题是,当我正在删除邻接并且从起始邻接之一操纵距离时,它似乎正在影响启动的其他邻接关系。因此,如果我穿过开始的北室,我最终到达一个房间,我从开始的西房间去了,那个房间的邻接区将会是0,因为西房间已经清除了它。
当我将start的每个邻接作为它自己的实体发送到方法中时,我不明白为什么会发生这种情况。任何见解都会有所帮助。
PS“start”和field是主类中的局部变量,不是类变量。