从char [] []数组提供规则创建邻接矩阵

时间:2015-07-05 22:33:26

标签: java arrays algorithm graph-theory adjacency-matrix

我想将char[][]数组(让我们称之为cA)更改为邻接矩阵。邻接矩阵的列和行等于数组中元素的数量,并且邻接矩阵中的每个顶点都是truefalse,这取决于初始数组中的元素是否相邻。我想稍微弯曲规则并将邻接矩阵顶点约束为true如果元素相邻其中一个元素不是特定值。

这是cA数组的样子:

z y z
z z z
z y y

aM数组的邻接矩阵(我们称之为cA)将是一个int大小为[3*3][3*3]的数组。 aM(i,j)true的条件是i数组中的元素jcA必须相邻,但i或{{}} {1}}可以" y"。

j数组元素1到9编号。

cA

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) iff aM(i,j) == 1i != j以及i != "y" && j != "y"i彼此相邻。

我难以调制算法来创建一个j数组的邻接矩阵。我已经定义了规则,但是找到迭代的约束是有问题的。

1 个答案:

答案 0 :(得分:2)

试试这个:

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