简体   繁体   中英

Implementation of Directed Weighted Graph

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;
  }   
 }
}
  • 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 and removeEdge should have some way to tell you if the edge was really added or removed. For example, return boolean true 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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