带权的无向图
#include<iostream>
using namespace std;
#define MAXVEX 100
#define INITMAX 65535
typedef char VerTexType;
typedef int EdgeType;
bool visited[MAXVEX] = { false };
class MGraph
{
public:
MGraph();
~MGraph();
void INITVIS();
void Dft(int v);
void Bft(int v);
void Print();
private:
VerTexType vex[MAXVEX];
EdgeType Edge[MAXVEX][MAXVEX];
int vexnum, edgenum;
};
MGraph::MGraph()
{
int j, k, w;
int f;
VerTexType c;
cout << "请输入顶点数和边数" << endl;
cin >> vexnum >> edgenum;
for (int i = 0; i < vexnum; i++) {
cout << "请输入第"<<i+1<<"个顶点信息" << endl;
cin >> c;
vex[i] = c;
}
for (int i = 0; i < MAXVEX; i++) {
for (int j = 0; j < MAXVEX; j++) {
if (i == j) {
Edge[i][j] = 0;
}
else {
Edge[i][j] = INITMAX;
}
}
visited[i] = false;
}
for (int i = 0; i < edgenum; i++) {
cout << "请输入边的下标i,j和权w" << endl;
cin >> f >> j >> w;
Edge[f][j] = w;
Edge[j][f] = Edge[f][j];
}
}
MGraph::~MGraph()
{
}
void MGraph::INITVIS()
{
for (int i = 0; i < MAXVEX; i++) {
visited[i] = false;
}
}
void MGraph::Dft(int v)
{
cout << vex[v] << " ";
visited[v] = true;
for (int i = 0; i < vexnum; i++) {
if (Edge[v][i] != INITMAX && visited[i] != true) {
Dft(i);
}
}
}
void MGraph::Bft(int v)
{
int w;
int Q[MAXVEX];
int front=-1,rear = -1;
cout << vex[v] << " ";
visited[v] = true;
Q[++rear] = v;
while (rear!=front)
{
w = Q[++front];
for (int j = 0; j < vexnum; j++) {
if (Edge[w][j] != INITMAX && visited[j] != true) {
cout << vex[j] << " ";
visited[j] = true;
Q[++rear] = j;
}
}
}
}
void MGraph::Print()
{
cout << "\t";
for (int i = 0; i < vexnum; i++) {
cout << vex[i] << "\t";
}
cout << endl;
for (int i = 0; i < vexnum; i++)
{
cout << vex[i] << "\t";
for (int k = 0; k < vexnum; k++) {
cout << Edge[i][k] << "\t";
}
cout << endl;
}
}
int main() {
MGraph G;
G.Print();
G.Dft(0);
G.INITVIS();
cout << endl;
G.Bft(0);
}
备考期末 学数字逻辑+离散