import java.util.Scanner;
public class Matrix {
Scanner scanner = new Scanner(System.in);
int temp = 0;
int[][] matrix;
int row;
public Matrix(int row) {
this.row = row;
matrix = new int[row][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
System.out.println("请输入第" + (i + 1) + "行第" + (j + 1) + "列元素(只能输入0和1两个数字):");
temp = scanner.nextInt();
if ( temp == 0 || temp == 1 )
matrix[i][j] = temp;
else {
System.out.println("输入有误,请重新输入");
j--;
}
}
}
}
public void display() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
System.out.print(matrix[i][j]);
if ( j == row - 1 )
System.out.print("\n");
else
System.out.print(" ");
}
}
}
public boolean reflexive() {
for (int i = 0; i < row; i++) {
if ( matrix[i][i] == 0 ) {
return false;
}
}
return true;
}
public boolean antiReflexive() {
for (int i = 0; i < row; i++) {
if ( matrix[i][i] == 1 ) {
return false;
}
}
return true;
}
public boolean symmetry() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
if ( matrix[i][j] != matrix[j][i] )
return false;
}
}
return true;
}
public boolean antiSymetry() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
if ( matrix[i][j] == matrix[j][i] && i != j )
return false;
}
}
return true;
}
public boolean transfer() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
if ( matrix[i][j] == 1 ) {
for (int k = 0; k < row; k++) {
if ( matrix[j][k] == 1 ) {
if ( matrix[i][k] == 0 ) {
return false;
}
}
}
}
}
}
return true;
}
public Matrix returnMatrix() {
return this;
}
public Matrix transitiveClosure() {
Matrix mat = this.returnMatrix();
for (int j = 0; j < mat.row; j++) {
for (int i = 0; i < mat.row; i++) {
if ( mat.matrix[i][j] == 1 ) {
for (int k = 0; k < mat.row; k++) {
mat.matrix[i][k] = Math.max(mat.matrix[i][k], mat.matrix[j][k]);
}
}
}
}
return mat;
}
public void transitiveClosureTostring() {
Matrix mat = this.transitiveClosure();
System.out.println("这个关系矩阵的传递闭包为:");
mat.display();
}
}
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int row;
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("请输入关系矩阵的阶数(输入0退出):");
row = scanner.nextInt();
if ( row == 0 )
return ;
Matrix matrix = new Matrix(row);
matrix.display();
if(matrix.reflexive())
System.out.println("该关系是自反");
else
System.out.println("该关系不是自反");
if(matrix.antiReflexive())
System.out.println("该关系是反自反");
else
System.out.println("该关系不是反自反");
if ( matrix.symmetry() )
System.out.println("该关系是对称");
else
System.out.println("该关系不是对称");
if ( matrix.antiSymetry() )
System.out.println("该关系是反对称");
else
System.out.println("该关系不是反对称");
if(matrix.transfer())
System.out.println("该关系是传递");
else
System.out.println("该关系不是传递");
matrix.transitiveClosureTostring();
}
}
}
2021-11-09
最新推荐文章于 2024-11-04 19:45:14 发布