我找到過一些程式,都是計算圖中的連通分量個數是多少,如下例子所示:
public class Demo{
static int[] hasFriend;
static int[][] Matrix;
static int length;
static int num = 0;
public static int findCircleNum(int[][] M) {
hasFriend = new int[M.length];
Arrays.fill(hasFriend, -1);
Matrix = M;
length = M.length;
for (int i = 0; i < length; i++) {
if (hasFriend[i] == -1) {
helper(i);
num++;
}
}
return num;
}
public static void helper(int i) {
hasFriend[i] = 1;
for (int j = 0; j < length; j++) {
if (Matrix[i][j] == 1 && i != j && hasFriend[j] == -1) {
helper(j);
}
}
}
public static void main(String[] args) {
int[][] matrix = {{0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
int maxSubNumber = findCircleNum(matrix);
//this output is: maxSubNumber:5
System.out.println("maxSubNumber:"+maxSubNumber);
}
}
但是我想得到最大連通子圖的數值,而不是聯通分量的個數,請問需要如何改寫呢?
StackOverflow地址:https://stackoverflow.com/q/62610977/11433138
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/34833.html
標籤:數據結構與算法
