繁体   English   中英

有向加权图(邻接矩阵)的实现

[英]Implementation of Directed Weighted Graph (Adjacent Matrix)

我需要帮助使用邻接矩阵在 java 中实现有向加权图。 不知道如何检查是否有连接的边或如何删除,只知道如何添加边。

// Implementation of directed weighted Graph using Adjacent Matrix

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;
    }

// need help in this function for what to set second line equal to or new function in general
public void removeEdge (int source, int destination, int weight) {
    if (source < size && source >= 0 && destination < size && destination >= 0)
        adjacentMatrix [source][destination] = 0;  //(not sure)
    }


//need help with this entire function
//function to check if edges are connected
public boolean isEdge(int source, int destination) {
    if(size >= 0 && size < size && destination >= 0 && destination < size) {
        if(adjacentMatrix[source][destination] == 1)
            return true;
        else
            return false;
     }
  }
 }   
}

 // I'm not sure if I did this correct at all any help would be appreciated

要删除边缘,您只需将相邻矩阵的单元格更改为 0(它处于默认阶段)。

你几乎想通了!

假设在您的邻接矩阵中,值 0 表示没有边,大于 0 的值表示存在具有该权重的边。

removeEdge方法不需要weight ,因为它会删除一条边。 此处设置为 0 是正确的,因为 0 表示“没有边缘”。

public void removeEdge (int source, int destination) {
    if (source < size && source >= 0 && destination < size && destination >= 0)
        adjacentMatrix [source][destination] = 0;
    }
}

由于您被告知在此处放置一个weight参数,因此可能是您应该仅在权重与传入的权重匹配时才删除边缘?

isEdge方法应该检查similarMatrix adjacentMatrix[source][destination] > 0而不是similarMatrix adjacentMatrix[source][destination] == 1 ,因为任何正值都意味着“那里有一条边”。

public boolean isEdge(int source, int destination) {
    if(size >= 0 && size < size && destination >= 0 && destination < size) {
        return adjacentMatrix[source][destination] > 0;
    } else {
        return false; // if out of range, no edge
    }
}

addEdge对权重没有限制,因此权重可以有任何值,包括 0。
所以 0 不是表示没有边的最佳选择。
我建议将权重设置为无限大。 在没有边缘的地方应用无限权重是有意义的:

adjacentMatrix [source][destination] =Integer.MAX_VALUE;

这可能需要在开始时将整个数组 nextMatrix adjacentMatrix[][]初始化为Integer.MAX_VALUE

  for(int[] row : adjacentMatrix)
        Arrays.fill(row, Integer.MAX_VALUE);
  }

isEdge也变得简单易读:

public boolean isEdge(int source, int destination) {
       if(size >= 0  
            && destination >= 0 && destination < size
            && source >= 0 && source < size ) 
                    return adjacentMatrix[source][destination] != Integer.MAX_VALUE;                        
        return false;            
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM