[英]Given an “Adjacency Matrix” representation of a an undirected graph BFS on the graph and output the vertex
[英]Why BFS stuck in Graph Node representation?
我使用节点和边缘 class 创建了图形。
当我从start = 0
调用traverseBFS
方法时。 然后它就卡住了。 无法进一步进行。 当我对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
Output
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]
节点 2 已连接:[到 1、到 5、到 3]
节点 3 已连接:[to 2, to 4, to 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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.