给出数字n(不超过10)和大小为n×n的矩阵。 检查此矩阵相对于主对角线是否对称。如果是对称的,则输出单词“ YES”,否则输出“ NO”。
这是我的代码,很不幸,它无法正常工作。请给我解释一下如何正确做:)
public class Main { public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n= scanner.nextInt();
int[][] number = new int[n][n];
boolean ismatch = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
number[i][j] = scanner.nextInt();
}
}
int unevenchecker = (n% 2);
if (unevenchecker != 0) {
for (int k = 0; k < number.length - 1; k++) {
for (int l = 0; l < number.length - 1; l++) {
if (number[k][l] == number[l][k]) {
ismatch = true;
}
}
}
if (ismatch) {
System.out.print("YES");
}
} else {
System.out.print("NO");
}
}
}
答案 0 :(得分:0)
如果找到至少1个对称对,其中2个部分不相等,则矩阵是不对称的,因此,代替检查循环内部的相等性,请检查不等式 >:
ismatch = true;
for (int k = 0; k < number.length - 1; k++) {
for (int l = 0; l < number.length - 1; l++) {
if (number[k][l] != number[l][k]) {
ismatch = false;
break;
}
}
}
答案 1 :(得分:0)
public class Main {
static boolean isSymmetric(int mat[][], int size) {
for (int i = 0; i < size; i++)
for (int j = i + 1; j < size - i; j++)
if (mat[i][j] != mat[j][i])
return false;
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n= scanner.nextInt();
int[][] number = new int[n][n];
boolean ismatch = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
number[i][j] = scanner.nextInt();
}
}
if (isSymmetric(number, n)) {
System.out.print("YES");
} else {
System.out.print("NO");
}
}
}
请注意,进入isSymmetric
的嵌套循环从j = i + 1
开始,因为没有检查两次相同的条件。