Question: Given the adjacent matrix of a non-simple graph, determine if the graph is a tree
Theorem 11 The graph is a tree when and only if there is a single simple path between each of its fixed points.
You can give an algorithm that uses breadth-first search to traverse all nodes and after accessing a node.
This node is no longer included in the node that is traversed later.
The algorithm is as follows:
Data structure: Whether the Mark array storage node has been traversed, 1 is not traversed, and 1 represents has been traversed
Relationstring contains elements in an array storage diagram
The first step:
Find a node as a tree root and mark all of its children as 1,
Step Two:
The above step produces all the children for the root node, and the breadth first searches for these children's nodes. If the newly accessed node is already accessed, the figure is not a tree,
The contrary marks these children for 1. and repeat this process until the descendants of all the root nodes are traversed.
Step three: Determine if the mark array contains a position labeled-1, and if so, the figure is not a tree.
The code is as follows.
Private Boolean Judge (string[] relationstring, int[][] Matrix, int[] mark,int bef, int aft) {
Find all pairings of the first element such as <a,b>
for (int i = 0; i < mark.length; i++) {
if (matrix[aft][i] = = 1) {//Retrieve new element
if (i = = bef) {
}//judge whether it is the edge that has been retrieved, judging is to jump directly on the line
else if (bef! = i) {//Is the new edge retrieved
if (mark[i] = = 1) {//with heavy edges
return false;
}
Mark[i] = 1;
if (! Judge (relationstring, Matrix, mark, aft, i)) {
return false;
}
}
}
}
return true;
}
Discrete mathematics the 11th chapter of computer Project 1th question