java实现有限集上给定关系的自反关系矩阵和对称闭包关系矩阵(附完整源码)
时间: 2023-10-28 18:13:46 浏览: 124
附上Java实现有限集上给定关系的自反关系矩阵和对称闭包关系矩阵的完整源码:
```java
public class RelationMatrix {
public static void main(String[] args) {
// 关系集合R
int[][] R = {{1, 2}, {2, 3}, {3, 1}, {1, 1}};
// 集合大小n
int n = 3;
// 输出关系矩阵R
System.out.println("关系矩阵R:");
int[][] RMatrix = relationMatrix(R, n);
printMatrix(RMatrix);
// 输出自反关系矩阵Rr
System.out.println("自反关系矩阵Rr:");
int[][] RrMatrix = reflexiveClosure(RMatrix, n);
printMatrix(RrMatrix);
// 输出对称闭包关系矩阵Rs
System.out.println("对称闭包关系矩阵Rs:");
int[][] RsMatrix = symmetricClosure(RMatrix, n);
printMatrix(RsMatrix);
}
/**
* 计算关系矩阵
*
* @param R 关系集合
* @param n 集合大小
* @return 关系矩阵
*/
public static int[][] relationMatrix(int[][] R, int n) {
int[][] matrix = new int[n][n];
for (int[] r : R) {
matrix[r[0] - 1][r[1] - 1] = 1;
}
return matrix;
}
/**
* 计算自反闭包
*
* @param matrix 关系矩阵
* @param n 集合大小
* @return 自反闭包矩阵
*/
public static int[][] reflexiveClosure(int[][] matrix, int n) {
int[][] closure = new int[n][n];
for (int i = 0; i < n; i++) {
closure[i][i] = 1;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
closure[i][j] = matrix[i][j] | closure[i][j];
}
}
return closure;
}
/**
* 计算对称闭包
*
* @param matrix 关系矩阵
* @param n 集合大小
* @return 对称闭包矩阵
*/
public static int[][] symmetricClosure(int[][] matrix, int n) {
int[][] closure = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
closure[i][j] = matrix[i][j] | matrix[j][i];
}
}
return closure;
}
/**
* 打印矩阵
*
* @param matrix 矩阵
*/
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
}
}
```
程序中实现了三个方法,其中relationMatrix用于计算关系矩阵,reflexiveClosure用于计算自反闭包,symmetricClosure用于计算对称闭包。程序先将关系集合转换为关系矩阵,然后分别计算自反闭包和对称闭包,并打印出结果。
阅读全文