我有一个图表示为邻接矩阵,我想找到两个节点之间的最短路径。该图是加权的。我想使用BFS算法,我尝试了但我用完了想法。这是我的代码,如果你能帮助我。找到2个节点之间的最短路径没有更多的想法
public class A {
private static int[][] adjacency = new int [4][4];
static int n = 4;
public static void main(String[] args) {
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
adjacency[i][j] = 0;
adjacency[0][1] = 2;
adjacency[0][3] = 1;
adjacency[1][0] = 2;
adjacency[1][2] = 5;
adjacency[2][1] = 5;
adjacency[2][3] = 1;
adjacency[2][4] = 2;
adjacency[3][0] = 1;
adjacency[3][2] = 1;
adjacency[4][2] = 2;
}
public List<Integer> getNeighbors(int node, int[][] a) {
List<Integer> list = new ArrayList<Integer>();
for(int i=0;i<n;i++)
if (a[node][i] != 0)
list.add(i);
return list;
}
public List<Queue<Integer>> findPath(int start, int end, int[][] a) {
List<Queue<Integer>> paths = new ArrayList<Queue<Integer>>();
Queue<Integer> toVisit = new LinkedList<Integer>();
Queue<Integer> visited = new LinkedList<Integer>();
toVisit.add(start);
while(!toVisit.isEmpty()) {
int node = toVisit.remove();
visited.add(node);
List<Integer> neighbors = new ArrayList<Integer>();
neighbors = this.getNeighbors(node,a);
}
return paths;
}
}
所以基本上我在想是要找到所有的2个给出节点之间的路径,并将其存储在队列的列表,然后检查其路径具有最短距离。你能帮我么。
BFS为等权在所有链路的最短路径算法,都是你的链接相同的权重? – Alejandro
http://en.wikipedia.org/wiki/Shortest_path_problem你读过那里吗?我记得Dijkstra和A *非常有效,虽然效率不高。 –
@ RB-Develop,我不认为他们被认为是寻找最短路径的“低效率”。如果你将BFS与Dijkstra/A *进行比较,那么苹果就不是苹果。 – Alejandro