java - Calculating weight of subgrah -
i need ask help, i've been struggling problem many days , didn't find suitable solution. want find weight of subgrah contains node (going parameter of method) , end central node 0. know sounds stupid image great here (http://img542.imageshack.us/img542/5400/zrzutekranu20130418o205.png). example getweight(8) return 21, same if run getweight(7) (9,10). getweight(2) = 7. wrote such method i'm getting stack overflow exception :(
private void getweight(object node, object source) { collection nodecollection = graph.getneighbors(node); (object n : nodecollection) { if ((integer) n == 0) { weight += ((myedge) (graph.findedge(startnode, node))).getw(); } else { if (n != source) { weight += ((myedge) (graph.findedge(node, n))).getw(); getweight(n, node); } else { } } } return weight; }
i'm using jung2 lib.
please help, last hope!
@zim-zam o'pootertoot: this?
arraylist<boolean> visited = new arraylist<boolean>(); public void getweight2(object i) { visited.set((integer) i, true); (object v : getgraph().getneighbors(i)) { if (!visited.get((integer) v)) { if (getgraph().getneighborcount(v) > 1 & !v.equals(startnode)) { weight += ((myedge) getgraph().findedge(i, v)).getw(); getweight2(v); } else { weight += ((myedge) getgraph().findedge(i, v)).getw(); } } } }
still soexp ;(
i don't know jung, pseudo java outlines way weight counting you're looking for, keeps maps track down visited nodes , visited edges (to avoid recounting of then), have fill in gaps api equivalent methods , make adjustments:
private int calculateweight(object startnode, hashmap<node, boolean> visitednodes, hashmap<edge, boolean> visitededges) { int w = 0; if (!visitednodes.get(startnode)) { // don't know if method (getedeges) exists, if implement // way edges go out node, paste code here // // edges node collection edges = startnode.getedges(); (object edge : edges) { // if edge haven't been visited, add weight w if (!visitededges.get(edge)) { w += edge.getw(); // mark edge visited visitededges.put(edge, true); } } // done node, mark visited visitednodes.put(startnode, true); // check neighbors of node recursively collection neighbornodes = getgraph().getneighbors(startnode); (object node : neighbornodes) { // go recursively node, passing in visited nodes , edges maps avoid recounting w += calculateweight(node, visitednodes, visitededges); } } return w; } // then, use above method public static void main(string... args) { hashmap<node, boolean> visitednodes = new hashmap<node, boolean>(); hashmap<edge, boolean> visitededges = new hashmap<edge, boolean>(); // search startnode , nodezero graph... // add node 0 visitednodes map, 0 node won't processed visitednodes.put(nodezero, true); int w = calculateweight(startnode, visitednodes, visitededges); }
warning: pseudo java, haven't test it
hope helps or @ least give hint solve problem
Comments
Post a Comment