簡體   English   中英

如何找到入射到特定頂點的邊列表

[英]How to find the list of edges incident to a particular vertex

我嘗試了以下但我不確定它是否正確。

ArrayList<ArrayList<Integer>> list = new ArrayList<>();
public static ArrayList<ArrayList<Integer>> incidentEdges(int v) {
   for(int i = 0; i < a.length; i++) {
      for(int j = 0; j < a[i].length; j++) {
         if(a[v][j] == 1) {
            list.get(v).get(new Edge(start, destination));
            list.get(j).get(new Edge(start, destination);
         }
      }
   }
   return list;
}

數組a是鄰接矩陣,參數v是無向圖的頂點。 如果頂點vj之間有一條邊,那么我們將邊添加到頂點v

方法一:查詢鄰接矩陣

由於您已經將邊存儲在鄰接矩陣中,因此您可以簡單地查詢它。 將你的i設置為 v (因為你一開始甚至沒有使用i ),然后檢查所有連接的頂點。

public static ArrayList<Integer> incidentEdges(int v) {
   ArrayList<Integer> result = new ArrayList<>();
   for(int i = 0; i < a[v].length; i++) {
     if(a[v][i] == 1) {
        result.add(a[v].get(i));
     }
   }
   return result;
}

方法 2:生成鄰接表

如果您控制了輸入(即在制作鄰接矩陣之前),您想要的是一個鄰接列表:其中每個list[start]指向一個ArrayList<Integer> (代表連接的頂點)。 我會避免使用ArrayList因為頂點的數量是已知的。 所以我會改用ArrayList<Integer>[] list 這無疑使編碼更容易。

這是從鄰接矩陣生成鄰接列表的示例

static ArrayList<Integer>[] list;

public static ArrayList<Integer>[] generateAl(int v) {
   list = new ArrayList[a.length];
   for(int i = 0; i < a.length; i++) {
      list[i] = new ArrayList<>();
      for(int j = 0; j < a[i].length; j++) {
         if(a[i][j] == 1) {
            list[i].add(j);
         }
      }
   }
   return list;
}

public static ArrayList<Integer> incidentEdges(int v) {
   return list[v];
}

暫無
暫無

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

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