参照此问题:https://www.cnblogs.com/mdumpling/p/9142410.html
写了个C#版本的,简单试了试,应该没问题
1 /// <summary> 2 /// 验证图是否为普通树 3 /// </summary> 4 /// <param name="n">图的节点数</param> 5 /// <param name="matrix">图的边集合</param> 6 /// <returns></returns> 7 private static bool GraphIsAOrdinaryTree(int n, int[,] matrix) 8 { 9 //(普通树:①没有回路 ②节点全连通 10 int row = matrix.GetLength(0);//边数 11 int column = matrix.GetLength(1); 12 if (column != 2)//只针对列数为2的矩阵 13 return false; 14 if (row != n - 1)//没有回路(边数=节点数-1)) 15 return false; 16 17 var startPoints = new List<int>(); 18 var endPoints = new List<int>(); 19 for (int i = 0; i < row; i++) 20 { 21 var num1 = matrix[i, 0]; 22 var num2 = matrix[i, 1]; 23 if (matrix[i, 0] < matrix[i, 1]) 24 { 25 startPoints.Add(num1); 26 endPoints.Add(num2); 27 } 28 else 29 { 30 startPoints.Add(num2); 31 endPoints.Add(num1); 32 } 33 } 34 if (startPoints.Union(endPoints).Distinct().Count() != n)//节点全连通(每个节点至少出现一次) 35 return false; 36 37 return true; 38 }