Determine whether a graph is a tree
problem
Given an undirected graph, we can judge whether the graph is a tree.
input
The input has several test samples. The first line is the number of test samples, followed by several test samples. The first line of each test sample is the node number n, and the nodes use 1,2 , n number. The second line is the number of sides m, followed by M node pairs.
output
If a graph is a tree, print "YES", otherwise print "NO". One line per output.
sample input
3 3 2 1 2 2 3 3 3 1 2 2 3 1 3 3 1 2 3
sample output
YES NO NO
Ideas:
A tree is a connected undirected graph without a simple circuit
Judgment method:
- Undirected graph is connected (judged by warshall algorithm)
- There is no simple circuit (according to the nature of the tree: a tree with n nodes contains n-1 edges)
code implementation
#include <stdio.h> //warshall algorithm / / pass closure void warshall(int matrix[][100],int size){ for(int j = 0; j < size; j ++){ for(int i = 0; i < size; i ++){ if(matrix[i][j] == 1){ for(int k = 0; k < size; k ++){ matrix[i][k] = matrix[j][k] || matrix[i][k]; } } } } } int main(){ int num; scanf("%d",&num);//Number of cycles for(int m = 0;m < num; m++){ int flag = 1; int mat[100][100] = {0}; int v,e; scanf("%d",&v);//Point scanf("%d",&e);//Edge number //Enter all sides for(int i = 0; i < e; i++){ int j,k; scanf("%d",&j); scanf("%d",&k); mat[j-1][k-1] = 1; mat[k-1][j-1] = 1; mat[i-1][i-1] = 1; } //1 determine whether there is a loop (the nature of the tree) if(v-e!=1){ flag = 0; } //2 determine whether it is connected (warshall pass closure) warshall(mat, v); for(int j = 0; j < v; j++){ for(int k = 0; k < v; k++){ if(mat[j][k]!=1){ flag = 0; } } } if(flag==0){ printf("NO\n"); }else{ printf("YES\n"); } } }