【问题标题】:Implementation of Directed Weighted Graph有向加权图的实现
【发布时间】:2020-04-08 20:29:57
【问题描述】:

想知道这里是否有任何不正确的地方。我得到的唯一没有添加的建议是将矩阵填充到 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;
  }   
 }
}

【问题讨论】:

    标签: java implementation adjacency-matrix directed-graph weighted-graph


    【解决方案1】:
    • isEdge 方法不考虑边可能具有负权重
    • 或者,如果不允许负权重,addEdge 应该检查权重是否为负数
    • addEdgeremoveEdge 应该有某种方法可以告诉您是否真的添加或删除了边缘。例如,如果修改了图形,则返回布尔值 true,或者如果不接受则抛出异常。
    • 您不能使用分数权重 - 也许这对您的用例来说没问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多