嘿伙计们我正在编写一个代码,它使用邻接矩阵检测有向图和未加权图是否为树,还打印叶节点。但我对解决问题的方式不太满意。那么,我怎样才能改进下面的代码片段。提前谢谢。
int check_tree(int graph[][MAX], int numberOfNodes, int leafNodes[]){
int noOfEdges = 0, i, j;
int visited[numberOfNodes];
for(i = 0; i < numberOfNodes; i++)
for(j = 0; j < numberOfNodes; j++)
if(graph[i][j]) noOfEdges++;
if(noOfEdges != numberOfNodes - 1) return 0; //in a tree, number of edges are always equal to no. of nodes - 1.
for(i = 0; i < numberOfNodes; i++)
visited[i] = 0; //setting all edges to zero meaning they are not visited.
visited[0] = 1; //parent node is always 1.
for(i = 0; i < numberOfNodes; i++)
for(j = 0; j < numberOfNodes; j++)
if(graph[i][j]) visited[j]++; //if [i][j] is 1 this means there is an edge an it is visited.
for(i = 0; i < numberOfNodes; i++)
if(visited[i] > 1) return 0; //this means the node is visited more than once which is not the case in a tree.
//if the code made it this far, we understand that it's a tree. so operations below are for tree.
int numberOfZeroIndex;
for(i = 0; i < numberOfNodes; i++){ // this loop detects the leaf nodes from adjacency matrix.
numberOfZeroIndex = 0; //make it zero in this step so that it will count correctly.
for(j = 0; j < numberOfNodes; j++){
if(!(graph[i][j])) numberOfZeroIndex++;
}
if(numberOfZeroIndex == numberOfNodes){
leafNodes[noOfLeafNodes] = i;
noOfLeafNodes++; //this one is a global variable to keep track of leaf nodes.
}
}
return 1;
}