java - 根据 char[][] 数组提供的规则创建邻接矩阵

标签 java arrays algorithm graph-theory adjacency-matrix

我想将一个char[][] 数组(我们称它为cA)变成一个邻接矩阵。邻接矩阵的列和行等于数组中元素的数量,邻接矩阵中的每个顶点要么是 true 要么是 false,具体取决于初始元素中的元素数组是相邻的。我想稍微改变一下规则,并将邻接矩阵顶点限制为真,前提是元素相邻并且其中一个元素不是特定值。

cA 数组如下所示:

z y z
z z z
z y y

cA 数组的邻接矩阵(我们称之为 aM)将是一个 int 数组,大小为 [3* 3][3*3]aM(i,j)true 的条件是 中的元素 ij >cA 数组必须相邻,但ij 都不能为"y"。

cA 数组元素从 1 到 9 编号。

1 2 3
4 5 6
7 8 9

aM 可以通过以下操作来描述:

aM(1,1) //false, no self-adjacency
aM(1,2) //false, 2 is a "y"
aM(1,3) //false, 1 is not adjacent to 3
aM(1,4) //true, 1 is adjacent to 4, neither are "y"
aM(1,5) //false, 1 is not adjacent to 5
aM(1,6) //false, 1 is not adjacent to 6
aM(1,7) through aM(1,9) //false, there is no adjacency between 1 and 7, 8, or 9
aM(2,1) through aM(2,9) //false, 2 is a "y"
...

希望你明白了。综上所述,cA 的邻接矩阵如下:

   1 2 3 4 5 6 7 8 9 (i)
 1 0 0 0 1 0 0 0 0 0
 2 0 0 0 0 0 0 0 0 0
 3 0 0 0 0 0 1 0 0 0
 4 1 0 0 0 1 0 1 0 0
 5 0 0 0 1 0 1 0 0 0
 6 0 0 1 0 1 0 0 0 0
 7 0 0 0 1 0 0 0 0 0
 8 0 0 0 0 0 0 0 0 0
 9 0 0 0 0 0 0 0 0 0
(j)

规则是 aM(i,j) == 1 当且仅当 i != j, i != "y"&& j != "y ",并且 ij 彼此相邻。

我在编造一个算法来创建一个提供 char[][] 数组的邻接矩阵时遇到了困难。我已经定义了规则,但是找到迭代的约束是有问题的。

最佳答案

试试这个:

static void set(boolean[][] aM, int cols, int row0, int col0, int row1, int col1) {
    int index0 = row0 * cols + col0;
    int index1 = row1 * cols + col1;
    aM[index0][index1] = aM[index1][index0] = true;
}

static boolean[][] adjacencyMatrix(char[][] cA) {
    int rows = cA.length;
    int cols = cA[0].length;
    boolean[][] aM = new boolean[rows * cols][rows * cols];
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            if (cA[i][j] == 'y')
                continue;
            if (i + 1 < rows && cA[i + 1][j] != 'y')
                set(aM, cols, i, j, i + 1, j);
            if (j + 1 < cols && cA[i][j + 1] != 'y')
                set(aM, cols, i, j, i, j + 1);
        }
    }
    return aM;
}

public static void main(String[] args) {
    char[][] cA = {
        {'z', 'y', 'z'},
        {'z', 'z', 'z'},
        {'z', 'y', 'y'},
    };
    boolean[][] aM = adjacencyMatrix(cA);
    for (boolean[] row : aM) {
        for (boolean cell : row)
            System.out.print(cell ? "1" : "0");
        System.out.println();
    }
}

结果是:

000100000
000000000
000001000
100010100
000101000
001010000
000100000
000000000
000000000

关于java - 根据 char[][] 数组提供的规则创建邻接矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235647/

相关文章:

java - 不使用 SSL 时抛出 "java.io.EOFException: SSL peer shut down incorrectly"

java - java中执行cmd命令获取时间

java - 为什么这个@JsonIgnore 修复了我的无限循环?

java - 将字符串数组的数组写入文件(txt、csv 等)

algorithm - 谷歌抓取索引算法

algorithm - 将 A* 搜索实现为广度优先搜索/深度优先搜索

java - 如何计算图像梯度

python - 将动态数字数组 reshape 为固定大小

java - 通过 REST Web 服务发送字节数组并接收字符串

算法复杂度: Strassen's algorithm is polynomially faster than n-cubed regular matrix multiplication. "polynomially faster"是什么意思?