[英]Implementation of Directed Weighted Graph
想知道这里是否有任何不正确的地方。 我得到的唯一没有添加的建议是将矩阵填充到 integer.max_value。 此外,权重必须是所有边的参数,当我们删除边时,权重变为 0,以防出现混淆。 如果您发现任何不正确的地方,请告诉我(java)。
public class Graph {
private int size;
private int adjacentMatrix[][];
public Graph (int size) {
this.size = size;
adjacentMatrix = new int [size][size];
}
public void addEdge (int source, int destination, int weight) {
if (source < size && source >= 0 && destination < size && destination >= 0)
adjacentMatrix [source][destination] = weight;
}
public void removeEdge (int source, int destination, int weight) {
if (source < size && source >= 0 && destination < size && destination >= 0)
adjacentMatrix [source][destination] = 0;
}
//function to check if edges are connected
public boolean isEdge(int source, int destination) {
if (source >= 0 && source < size && destination >= 0 && destination < size) {
return adjacentMatrix[source][destination] > 0;
}
else
return false;
}
}
}
isEdge
方法没有考虑边可能有负权重addEdge
应该检查权重是否为负addEdge
和removeEdge
应该有一些方法可以告诉您边缘是否真的被添加或删除。 例如,如果修改了图形,则返回 boolean true
,否则如果不接受则抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.