連通図かどうかを検出する(深さ優先ループアルゴリズム)
(一)九度前の練習問題
タイトルの説明:
無方向図とその中のすべてのエッジを与えて、この図がすべての頂点が連通しているかどうかを判断します.
入力:
各データ群の最初の行は2つの整数nとm(0<=n<=1000)である.nは図の頂点数を表し、mは図中の辺の数を表す.nが0であると入力が終了する.その後、m行のデータがあり、各行に2つの値xとy(0
出力:
入力データのセットごとに、すべての頂点が接続されている場合は「YES」、そうでない場合は「NO」が出力されます.
サンプル入力:
サンプル出力:
(二)図が連通しているか否かを判断するには、深さ優先遍歴の方法で判断することができる.具体的には、図中にいずれかの頂点を選択し、その頂点を深さ優先遍歴し、この遍歴中にすべての頂点が遍歴されると、その図が連通となる.逆に、遍歴されていない頂点が存在すると、その図が非連通であることを説明する.現代コードは以下の通り(無方向図に対して隣接表構造を用いる):
タイトルの説明:
無方向図とその中のすべてのエッジを与えて、この図がすべての頂点が連通しているかどうかを判断します.
入力:
各データ群の最初の行は2つの整数nとm(0<=n<=1000)である.nは図の頂点数を表し、mは図中の辺の数を表す.nが0であると入力が終了する.その後、m行のデータがあり、各行に2つの値xとy(0
出力:
入力データのセットごとに、すべての頂点が接続されている場合は「YES」、そうでない場合は「NO」が出力されます.
サンプル入力:
4 3
1 2
2 3
3 2
3 2
1 2
2 3
0 0
サンプル出力:
NO
YES
(二)図が連通しているか否かを判断するには、深さ優先遍歴の方法で判断することができる.具体的には、図中にいずれかの頂点を選択し、その頂点を深さ優先遍歴し、この遍歴中にすべての頂点が遍歴されると、その図が連通となる.逆に、遍歴されていない頂点が存在すると、その図が非連通であることを説明する.現代コードは以下の通り(無方向図に対して隣接表構造を用いる):
#include
#include
using namespace std;
#define MAX_NODE 1000
typedef struct ArcNode
{
int adjvex;// ( )
ArcNode* next;//
ArcNode(int value)
{
adjvex = value;
next = NULL;
}
};//
typedef struct
{
int vexdata; //
struct ArcNode* firstarc;//
}VexNode, AdjList[MAX_NODE];//
typedef struct
{
AdjList vexNodes;
int vexNum;
int arcNum;//
}GraphWithAL;//
// ,
bool CheckArcIsExist(GraphWithAL* G, int v1, int v2)
{
ArcNode* temp = G->vexNodes[v1-1].firstarc;
while(temp!=NULL)
{
if(temp->adjvex == v2)
return true;
temp = temp->next;
}
return false;
}
// ,vexNum ,arcNum ,isUnDirected
void CreateGraph(GraphWithAL* G, int vexNum, int arcNum, bool isUnDirected)
{
memset(G, 0 ,sizeof(GraphWithAL));
//
int i = 0;
for(i=0; ivexNum = vexNum;
G->vexNodes[i].firstarc = NULL;
G->vexNodes[i].vexdata = i+1;// 1
}
//
for(i=0; i>v1>>v2;
if(CheckArcIsExist(G, v1, v2))
continue;
ArcNode* arcNode = new ArcNode(v2);
// ,
arcNode->next = G->vexNodes[v1-1].firstarc;
G->vexNodes[v1-1].firstarc = arcNode;
G->arcNum++;
if(isUnDirected)
{
ArcNode* arcNode = new ArcNode(v1);
// ,
arcNode->next = G->vexNodes[v2-1].firstarc;
G->vexNodes[v2-1].firstarc = arcNode;
}
}
}
// vex , visit true
void DFS(GraphWithAL* G, int vex, bool* visit)
{
//cout<vexNodes[vex-1].firstarc;
if(temp == NULL)
{
//cout<null"<adjvex-1])
{
//cout<"<adjvex<adjvex-1] = true;
DFS(G, temp->adjvex, visit);
}
temp = temp->next;
}
}
//
void DFS_Visit(GraphWithAL* G)
{
bool* visit = new bool[G->vexNum];
memset(visit, 0, G->vexNum);
int i=0;
for(i=0; ivexNum; ++i)
{
if(!visit[i])
DFS(G, i+1, visit);
}
}
//
bool CheckGraphIsConnected(GraphWithAL* G)
{
bool* visit = new bool[G->vexNum];
memset(visit, 0, G->vexNum);
DFS(G, 1, visit);
int i=0;
for(i=0; i>n>>m)
{
if(n==0)
break;
CreateGraph(&G, n, m, true);
//DFS_Visit(&G);
//
bool flag = CheckGraphIsConnected(&G);
if(flag)
cout<