Java 根据char[][]数组提供的规则创建邻接矩阵
我想将一个Java 根据char[][]数组提供的规则创建邻接矩阵,java,arrays,algorithm,graph-theory,adjacency-matrix,Java,Arrays,Algorithm,Graph Theory,Adjacency Matrix,我想将一个char[][]数组(称之为cA)更改为邻接矩阵。邻接矩阵的列和行数等于数组中的元素数,邻接矩阵中的每个顶点是true或false,具体取决于初始数组中的元素是否相邻。我想稍微改变一下规则,并在元素相邻且其中一个元素不是特定值时,将邻接矩阵顶点约束为true 下面是cA数组的外观: z y z z z z z y y cA数组的邻接矩阵(称之为aM)将是大小为[3*3][3*3]的int数组。aM(i,j)为true的条件是cA数组中的元素i和j必须相邻,但i或j都不能为“y” 让我
char[][]
数组(称之为cA
)更改为邻接矩阵。邻接矩阵的列和行数等于数组中的元素数,邻接矩阵中的每个顶点是true
或false
,具体取决于初始数组中的元素是否相邻。我想稍微改变一下规则,并在元素相邻且其中一个元素不是特定值时,将邻接矩阵顶点约束为true
下面是cA
数组的外观:
z y z
z z z
z y y
cA
数组的邻接矩阵(称之为aM
)将是大小为[3*3][3*3]
的int
数组。aM(i,j)
为true
的条件是cA
数组中的元素i
和j
必须相邻,但i
或j
都不能为“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
iffi!=j
,i!=y&j!=“y”
,以及i
和j
都是相邻的
我很难用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();
}
}
太好了,这个效果非常好。我注意到所有的邻接矩阵都是沿着对角线对称的,对角线总是
{0}
(除非有可能实现自邻接,否则它就是{1}
)。只计算上三角矩阵的aM(i,j)然后复制到下三角矩阵会更有效吗aM(i,j)
始终等于aM(j,i)
。请参见我的代码第4行(aM[index0][index1]=aM[index1][index0]=true;
)。该算法只计算单向邻接。结果存储在两个位置aM(i,j)
和aM(j,i)
。如果将结果矩阵更改为三角形,则可以节省内存,但不能节省时间。
000100000
000000000
000001000
100010100
000101000
001010000
000100000
000000000
000000000