簡體   English   中英

如何在Graph中創建相對於距離從單個節點傳播的邊

[英]How to create edges propagating from a single node with respect to distance in a Graph

我有一個圖表,我需要創建從單個節點到有一定距離的節點的有向邊,從初始節點指向距離內的節點。 然后,它從距離初始節點到這些節點距離內的節點的節點創建邊緣,並且一直持續到每個節點至少有一個邊緣。

我在代碼中將其概念化並將其付諸實踐存在問題。 我有以下代碼當前哪種工作但不夠好,因為有時遠離初始節點的節點不會獲得邊緣:

//create patient zero
    graphVer.get(0).getValue().setInfected(true);
    graphVer.get(0).getValue().setRecentlyInfected(true);
    graphVer.get(0).getValue().setLevel(0);
    for(int i = 0; i < graphVer.size();i++) {
        for(int j = 0; j < graphVer.size();j++) {
            //checks each vertex against every other vertex, and if their distance is within limits and they aren't equal to each other, then create an edge between them
            if(distance(graphVer.get(i).getValue().getX(), graphVer.get(i).getValue().getY(),graphVer.get(j).getValue().getX(),graphVer.get(j).getValue().getY()) < dis.getRange()) {
                if(i != j) {
                    //makes sure that there is only one edge between two nodes and directs it based on where patient zero is
                    if(graphVer.get(i).getValue().getLevel() <= i && graphVer.get(j).getValue().getLevel() > graphVer.get(i).getValue().getLevel()) {
                        graphEdge.add(new Edge<>(0,graphVer.get(i),graphVer.get(j)));
                        graphVer.get(j).getValue().setLevel(i+1);
                    }
                }
            }
        }
    }

我沒有包含頂點創建的代碼,它只是在方形邊界內隨機創建頂點,確保沒有重疊。 graphVer是圖中所有頂點的arraylist,graphEdge是圖中所有邊的arraylist。

有什么更好的方法來做到這一點,每次都能正常工作?

您的措辭有點令人困惑,您是不是只想到達距離原始節點一定距離的節點? 如果是這種情況,那么“有時遠離初始節點的節點不會獲得邊緣”將是您想要發生的。

我在評論中指出了你的問題規范中的缺點。

從概念上講,我認為你想要的是從所有邊(v,w)的圖G開始,其中dist(v,w)<= DIST。 這將包含許多周期。 在此圖中,您希望通過首先從起始頂點搜索寬度來查找發現的樹T.

為了實現這一點,你不需要構造G.正如你所推斷的那樣,你可以迭代所有頂點對並用dist(v,w)<= DIST測試它們以發現G中的邊緣,因為它們是需要的。

BFS使用隊列。 你最終會得到這個算法:

Let x be the start vertex
Let N be a set initially containing all vertices (not yet infected)
Let Q be a queue for vertices
Let T be the initially empty set of tree edges
Add x to Q and remove it from N // Infect x.
while Q is not empty
  Pop vertex v from the head of Q
  for each vertex w in N // Iterate through all non-infected vertices
    if dist(v, w) < DIST
      Add edge v->w to T // w is now infected
      add w to the tail of Q
      remove w from N
return T

這幾乎可以逐行轉換為Java。

請注意,輸出必須是樹,因為每個頂點w只能從N中刪除一次。 因此,在T中只能有一個形式為v-> w的邊。這意味着每個頂點最多只有一個父節點,這是定向樹的定義。

正如我在評論中所說,如果它們之間的間隙太大,則不能保證它將包括樹中的所有頂點。

只是為了好玩,這里是隨機定位頂點的示例輸出。 起始頂點是左上角的雙倍大小。

請注意不包括頂點,因為它們距離任何感染源都太遠。 這是對的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM