/*The weighted undirected graph in lists form *-check interface for notes. */ package graphADT; import java.util.ArrayList; import java.io.*; public class wUGraphLists extends wGraphLists implements wUGraph { public wUGraphLists() { super(); } public wUGraphLists(wUGraphLists G) //copy { super(G); } public wUGraphLists(Graph G) { int n = G.order(); addVertices(n); //first make it undirected // for (int i=0; i nbrs = G.neighbors(i); for (int j : nbrs) { super.addArc(i,j); super.addArc(j,i); } } // then create a weighted graph by giving all edges the default weight. // for (int i=0; i nbrs = G.neighbors(i); ArrayList wNbrs = new ArrayList(); for (int j = 0; j < nbrs.size(); j++) { wNbrs.add(new Weight(1)); } adj.add(nbrs); adjWei.add(wNbrs); } } public wUGraphLists(BufferedReader buffer) { //input is given in the form //n //[line 0] nei_0 wei_0 nei_1 wei_1...nei_n-1 wei_n-1 //[line 1] nei_0 wei_0 nei_1 wei_1...nei_n-1 wei_n-1 //... //[line n-1] nei_0 wei_0 nei_1 wei_1...nei_n-1 wei_n-1 super(buffer); } public void addArc(int i, int j) { assert(0 <= i && i < order()); assert(0 <= j && j < order()); if (!isArc(i,j)) { (adj.get(i)).add(j); (adjWei.get(i)).add(new Weight(1)); //default weight } if (!isArc(j,i)) { (adj.get(j)).add(i); (adjWei.get(j)).add(new Weight(1)); //default weight } } public void removeArc(int i, int j) { assert(0 <= i && i < order()); assert(0 <= j && j < order()); if (isArc(i,j)) { ArrayList temp = adj.get(i); int place = adj.indexOf(new Integer(j)); temp.remove(place); //the integer j adjWei.get(i).remove(place); //its weight } if (isArc(j,i)) { ArrayList temp = adj.get(j); int place = adj.indexOf(new Integer(i)); temp.remove(place); //the integer i adjWei.get(j).remove(place); //its weight } } @SuppressWarnings("unchecked") public void addArc(int i, int j, Weight weight) { assert(0 <= i && i < order()); assert(0 <= j && j < order()); if (!isArc(i,j)) //don't add the same edge twice { (adj.get(i)).add(j); (adjWei.get(i)).add(weight); } if (!isArc(j,i)) { (adj.get(j)).add(i); (adjWei.get(j)).add(weight); } if (isArc(i,j)) //if it exists just change the weight { int place = (adj.get(i)).indexOf(new Integer(j)); adjWei.get(i).set(place, weight); } if (isArc(j,i)) { int place = (adj.get(j)).indexOf(new Integer(i)); adjWei.get(j).set(place, weight); } } @SuppressWarnings("unchecked") public void setArcWeight(int i, int j, Weight weight) { assert(isArc(i, j)); int place_i = (adj.get(i)).indexOf(new Integer(j)); adjWei.get(i).set(place_i, weight); assert(isArc(j, i)); int place_j = (adj.get(j)).indexOf(new Integer(i)); adjWei.get(j).set(place_j, weight); } public int size() { return super.size()/2; //extends the wGraph[Implementation] } }