任务是
"You've got a adjacency matrix (nxn). And simple graph. Print YES, if the graph is undirected and NO otherwise."
我的老师说这个程序不正确。为什么?
import java.util.Scanner;
public class Graph {
private static Scanner scan;
public static void main(String[] args){
scan = new Scanner(System.in);
final int n = scan.nextInt();
Graph graph = new Graph();
int[][] matrix = graph.createMatrix(n);
boolean truth = graph.checkoriented(matrix);
System.out.println((truth)? "Yes": "No");
scan.close();
}
private boolean checkoriented(int[][] matrix) {
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix.length; j++){
if(matrix[i][j] == 1){ //look if element on i pow, j column is "1";
boolean way = (matrix[j][i] == 1)? true: false; //if element on j pow i locumn is 1 also
if(!way) return false; // if element on j pow i locumn is 0 graph is oriented
}
}
}
return true;
}
private int[][] createMatrix(int n) {
int[][] matrix = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
matrix[i][j] = scan.nextInt();
}
}
return matrix;
}
}
最佳答案
我不知道这是否真的是一个问题,但如果你的输出应该是YES
或NO
,你最好打印这些而不是Yes
和 No
System.out.println((truth)? "Yes": "No");
。
PS:如果您的图有一条从顶点到同一个顶点的路径(我的意思是matrix[i][i] = 1
),您的算法可能会认为该图是无向的,但事实并非如此。
关于java - 检查简单图是否有向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40791283/