一、题目
二、使用BFS解题
1.Link_Graph.h
#include <iostream>
#include <queue>
using namespace std;
#define N 100
#define WHITE 0
#define GRAY 1
#define BLACK 2
queue<int> Q;
class Mat_Graph
{
public:
int n;
int color[N+1];
int d[N+1];
int Pie[N+1];
int Map[N+1][N+1];
Mat_Graph(int num):n(num)
{
memset(Map, 0, sizeof(Map));
}
void AddDoubleEdge(int a, int b, int value = 1)
{
AddSingleEdge(a, b, value);
AddSingleEdge(b, a, value);
}
void AddSingleEdge(int start, int end, int value = 1)
{
Map[start][end] = value;
}
void DeleteDoubleEdge(int a, int b)
{
DeleteSingleEdge(a, b);
DeleteSingleEdge(b, a);
}
void DeleteSingleEdge(int start, int end)
{
Map[start][end] = 0;
}
//22.2-3
void BFS(int s);
void Print_Path(int s, int v);
};
void Mat_Graph::BFS(int s)
{
int u, v;
for(u = 1; u <= n; u++)
{
color[u] = WHITE;
d[u] = 0x7fffffff;
Pie[u] = 0;
}
color[s] = GRAY;
d[s] = 0;
Pie[s] = 0;
while(!Q.empty())Q.pop();
Q.push(s);
while(!Q.empty())
{
u = Q.front();Q.pop();
for(v = 1; v <= n; v++)
{
if(Map[u][v] == 0)continue;
if(color[v] == WHITE)
{
color[v] = GRAY;
d[v] = d[u] + 1;
Pie[v] = u;
Q.push(v);
}
}
color[u] = BLACK;
}
}
void Mat_Graph::Print_Path(int s, int v)
{
BFS(s);
if(v == s)
cout << s<<' ';
else
{
if(Pie[v] == 0)
cout<<"no path from "<<s<<" to "<<v<<" exists."<<endl;
else
{
Print_Path(s, Pie[v]);
cout<<v<<' ';
}
}
}
2.main.cpp
#include <iostream>
#include "Link_Graph.h"
using namespace std;
int main()
{
int i = 0, a, b, n, r;
cin>>n>>r;
Link_Graph *G = new Link_Graph(8);
for(i = 1; i <= r; i++)
{
cin>>a>>b;
//无向图
G->AddDoubleEdge(a,b);
}
G->BFS_Init();
bool ret = true;
for(i = 1; i <= n; i++)
{
if(G->V[i].color == WHITE && G->V[i].type == UNDEFINED)
ret = G->BFS(i);
if(ret == false)
{
cout<<"error"<<endl;
return 0;
}
}
for(i = 0; i <= n; i++)
{
switch (G->V[i].type)
{
case GOOD:
cout<<i<<" is a good player."<<endl;
break;
case BAD:
cout<<i<<" is a bad player."<<endl;
break;
}
}
delete G;
return 0;
}