英文:
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;
}
}
}
英文:
Want to know if there was anything here that seems incorrect. The only suggestion I have gotten that I havent added was to fill the matrix to integer.max_value. Also the weight has to be the parameter for all edges and weight goes to 0 when we remove edge just in case there is confusion. If you see anything incorrect please let me know (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;
}
}
}
答案1
得分: 0
isEdge
方法未考虑边缘可能具有负权重。- 或者,如果不允许负权重,则
addEdge
应检查权重是否为负数。 addEdge
和removeEdge
应该有某种方式告诉您是否真正添加或删除了边缘。例如,如果图已修改,则返回布尔值true
,或者如果不被接受,则抛出异常。- 您不能具有分数权重 - 或许这对于您的用例来说是可以的。
英文:
- The
isEdge
method does not take into account that edges may have negative weights - OR, if negative weights are not allowed,
addEdge
should check if the weight is negative addEdge
andremoveEdge
should have some way to tell you if the edge was really added or removed. For example, return booleantrue
if the graph was modifed, OR throw an exception if not accepted.- You can't have fractional weights - maybe that's ok for your use case.
专注分享java语言的经验与见解,让所有开发者获益!
评论