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;
}
}
}
isEdge
method does not take into account that edges may have negative weights addEdge
should check if the weight is negativeaddEdge
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.
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.