我已经使用Node和Edge类创建了图形。
当我调用 traverseBFS
方法从 start = 0
然后就卡住了,无法继续进行。当我使用类似的方法与 HashMap<Integer,ArrayList<Integer>>
这个算法正常运行。请帮助我如何解决这个问题。
完整代码
import java.util.*;
import java.io.*;
public class Dijkstra {
static class Node {
public int id;
public long dist;
public int par;
public Node(int a, long d, int b) {
id = a;
dist = d;
par = b;
}
}
static class Edge {
int to;
int weight;
public Edge(int a, int b) {
to = a;
weight = b;
}
}
static int vert;
static ArrayList<LinkedList<Edge>> list;
static int[] parent;
static long[] distance;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
vert = sc.nextInt();
int edges = sc.nextInt();
list = new ArrayList<>();
parent = new int[vert + 1];
distance = new long[vert + 1];
for (int i = 0; i <= vert; i++) {
list.add(i, new LinkedList<Edge>());
}
for (int i = 0; i < edges; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
int w = sc.nextInt();
list.get(u).add(new Edge(v, w));
list.get(v).add(new Edge(u, w));
}
traverseBFS(0);
}
public static void traverseBFS(int start) {
System.out.print("\nBFS >> \n");
boolean visited[] = new boolean[vert];
LinkedList<Integer> q = new LinkedList<>();
q.add(start);
visited[start] = true;
while (!q.isEmpty()) {
int s = q.poll();
System.out.print(s + " ");
LinkedList<Edge> temp = list.get(s);
for (Edge var : temp) {
if (!visited[var.to]) {
visited[var.to] = true;
q.add(var.to);
}
}
}
}
}
输入
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
产量
BFS >>
0
发布时 mre 考虑对测试数据进行硬编码,以方便运行测试。
public static void main(String[] args) {
int[][] neighbours = {
{1,2,2},
{2,5,5},
{2,3,4},
{1,4,1},
{4,3,3},
{3,5,1}
};
vert = 5;
list = new ArrayList<>();
parent = new int[vert + 1];
distance = new long[vert + 1];
for (int i = 0; i <= vert; i++) {
list.add(i, new LinkedList<Edge>());
}
for (int i = 0; i < neighbours.length; i++) {
int u = neighbours[i][0];
int v = neighbours[i][1];
int w = neighbours[i][2];
list.get(u).add(new Edge(v, w));
list.get(v).add(new Edge(u, w));
}
traverseBFS(0);
}
一个简单的打印出来的图形创建 显示节点0没有连接到任何其他节点。
节点0连接: [] 节点1连接: [至2,至4] 节点0连接: [到2,到4] 节点2连接。[到1,到5,到3] 节点3连接。[至2,至4,至5] 节点4连接。[至1,至3] 节点5连接。[至2,至3]
为简化打印输出,添加 toString
方法到Edge。
static class Edge {
int to;
int weight;
public Edge(int a, int b) {
to = a;
weight = b;
}
@Override
public String toString() {
return "to "+to;
}
}
并使用
for(int node = 0; node < list.size(); node ++){
System.out.println("Node "+node +" connected: " + list.get(node));
}