【发布时间】:2015-07-07 13:39:59
【问题描述】:
我有一个邻接矩阵 adj,定义如下:
0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0
1 0 0 0 1 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 1 0 0 0 1
0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0
我正在绞尽脑汁设计一个 BFS 算法来遍历给定起始位置和结束位置的图。
我的最佳尝试确实产生了一系列动作,但不是最短的。
boolean[] pass = new boolean[9]; //if a move has been done, don't redo it
int s = 0; //starting position
int e = 2; //ending position
int[][] matrix; //the adjacency matrix previous defined
public List<Integer> BFS(int[][] matrix, int s) {
List<Integer> paths = new LinkedList();
List<Integer> shortest = new LinkedList();
pass[s] = true; //starting position has been indexed
paths.add(0,s); //insert part of path to front of list
while (paths.isEmpty() == false) {
int element = paths.get(0); //peek at first element
shortest.add(element); //add it to shortest path
int node = paths.remove(0); //remove from path
if (element == e) { //if we've reached the end
return shortest; //hopefully found shortest path
} else {
for (int i = 0; i < 9; i++) {
//if adjacent element hasn't been indexed
if (pass[i] == false && matrix[node][i] == 1) {
pass[i] = true;
paths.add(0,i);
}
}
}
}
return null;
}
打印返回的列表产生:
[0, 3, 6, 4, 5, 8, 2]
实际结果应该是什么时候:
[0, 3, 4, 5, 2]
在我看来,它所走的道路是这样的:
[0, 3, 6, backtrack to 3, 4, 5, 8, backtrack to 5, 2]
我的算法有什么问题?如何找到给定起点和终点的最短路径?
Here 是一个用于说明的 IDE。
【问题讨论】:
-
你的 BFS 遍历没问题,但是你没有正确提取最短路径。您正在将您处理的 每个 节点添加到最短路径。
标签: java algorithm search graph-theory adjacency-matrix