簡體   English   中英

有向加權圖(鄰接矩陣)的實現

[英]Implementation of Directed Weighted Graph (Adjacent Matrix)

我需要幫助使用鄰接矩陣在 java 中實現有向加權圖。 不知道如何檢查是否有連接的邊或如何刪除,只知道如何添加邊。

// Implementation of directed weighted Graph using Adjacent Matrix

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;
    }

// need help in this function for what to set second line equal to or new function in general
public void removeEdge (int source, int destination, int weight) {
    if (source < size && source >= 0 && destination < size && destination >= 0)
        adjacentMatrix [source][destination] = 0;  //(not sure)
    }


//need help with this entire function
//function to check if edges are connected
public boolean isEdge(int source, int destination) {
    if(size >= 0 && size < size && destination >= 0 && destination < size) {
        if(adjacentMatrix[source][destination] == 1)
            return true;
        else
            return false;
     }
  }
 }   
}

 // I'm not sure if I did this correct at all any help would be appreciated

要刪除邊緣,您只需將相鄰矩陣的單元格更改為 0(它處於默認階段)。

你幾乎想通了!

假設在您的鄰接矩陣中,值 0 表示沒有邊,大於 0 的值表示存在具有該權重的邊。

removeEdge方法不需要weight ,因為它會刪除一條邊。 此處設置為 0 是正確的,因為 0 表示“沒有邊緣”。

public void removeEdge (int source, int destination) {
    if (source < size && source >= 0 && destination < size && destination >= 0)
        adjacentMatrix [source][destination] = 0;
    }
}

由於您被告知在此處放置一個weight參數,因此可能是您應該僅在權重與傳入的權重匹配時才刪除邊緣?

isEdge方法應該檢查similarMatrix adjacentMatrix[source][destination] > 0而不是similarMatrix adjacentMatrix[source][destination] == 1 ,因為任何正值都意味着“那里有一條邊”。

public boolean isEdge(int source, int destination) {
    if(size >= 0 && size < size && destination >= 0 && destination < size) {
        return adjacentMatrix[source][destination] > 0;
    } else {
        return false; // if out of range, no edge
    }
}

addEdge對權重沒有限制,因此權重可以有任何值,包括 0。
所以 0 不是表示沒有邊的最佳選擇。
我建議將權重設置為無限大。 在沒有邊緣的地方應用無限權重是有意義的:

adjacentMatrix [source][destination] =Integer.MAX_VALUE;

這可能需要在開始時將整個數組 nextMatrix adjacentMatrix[][]初始化為Integer.MAX_VALUE

  for(int[] row : adjacentMatrix)
        Arrays.fill(row, Integer.MAX_VALUE);
  }

isEdge也變得簡單易讀:

public boolean isEdge(int source, int destination) {
       if(size >= 0  
            && destination >= 0 && destination < size
            && source >= 0 && source < size ) 
                    return adjacentMatrix[source][destination] != Integer.MAX_VALUE;                        
        return false;            
}

暫無
暫無

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

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