检查星形图


给定一个图,我们必须检查给定的图是星形图还是不是。

通过遍历图,我们必须找到度数为 1 的顶点数和度数为 n-1 的顶点数。(此处 n 为给定图中的顶点数)。当具有度数 1 的顶点数为 n-1 且具有度数 (n-1) 的顶点数为 1 时,则该图是星形图。

输入和输出

Input:
The adjacency matrix:
0 1 1 1
1 0 0 0
1 0 0 0
1 0 0 0

Output:
It is a star graph.

算法

checkStarGraph(graph)

输入:给定的图。

输出:当图是星形图时返回 True。

Begin
   degOneVert := 0 and degNminOneGraph := 0
   if graph has only one vertex, then
      return true, if there is no self-loop
   else if graph has two vertices, then
      return true if there is only one vertex between two vertices
   else
      for all vertices i in the graph, do
         degree := 0
         for all vertices j, adjacent with i, do
            degree := degree + 1
         done
         if degree = 1, then
            degOneVert := degOneVert + 1
         else if degree = n-1, then
            degNminOneGraph := degNminOneGraph + 1
      done

   if degOneVert = n-1, and degNminOneGraph = 1, then
      return true
   otherwise return false
End

示例

#include<iostream>
#define NODE 4
using namespace std;

int graph[NODE][NODE] = {
   {0, 1, 1, 1},
   {1, 0, 0, 0},
   {1, 0, 0, 0},
   {1, 0, 0, 0}
};

bool checkStarGraph() {
   int degOneVert = 0, degVert = 0;    //initially vertex with degree 1 and with degree n - 1 are 0
   if (NODE == 1)    //when there is only one node
      return (graph[0][0] == 0);

   if (NODE == 2)  
      return (graph[0][0] == 0 && graph[0][1] == 1 && graph[1][0] == 1 && graph[1][1] == 0 );

   for (int i = 0; i < NODE; i++) {    //for graph more than 2
      int degree = 0;
      for (int j = 0; j < NODE; j++)    //count degree for vertex i
         if (graph[i][j])
            degree++;
      if (degree == 1)
         degOneVert++;
      else if (degree == NODE-1)
         degVert++;
   }
   //when only vertex of degree n-1, and all other vertex of degree 1, it is a star graph
   return (degOneVert == (NODE-1) && degVert == 1);
}

int main() {
   if(checkStarGraph())
      cout << "It is a star graph.";
   else
     cout << "It is not a star graph.";
}

输出

It is a star graph.

更新于: 16-6-2020

540 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始
广告