邻接矩阵构造图,广度、深度遍历

#include<iostream>

using namespace std;

struct Node

{

int  vertex;//存放顶点

Node *next;

};

class queen

{

public:

queen();

void enqueen(int j);//入队操作,将元素j入队

int dequeen();//出队操作,将队头元素出队

bool isempty()

{

if (front == rear)

return true;

else

return false;

}

private:

Node* front, *rear;

Node *s;//临时结点

};

queen::queen()

{

s = new Node;

s->next = NULL;

front = rear = s;

};

void queen::enqueen(int j)//有头结点的空链队列和非空链队列的入队操作语句是一样的

{

s = new Node;

s->vertex = j;

s->next = NULL;

rear->next = s;

rear = s;

}

int queen::dequeen()

{

if (front == rear)

throw”下溢”;

s = front->next;

//s->bt = cha;

int x;

x = s->vertex;

front->next = s->next;

if (s->next == NULL)//判断出出队前队列长度是否为1

rear = front;

delete s;

return x;

}

const int maxsize = 4;

class Mgraph

{

public:

Mgraph(char a[], int n, int e);//构造函数,建立具有n个顶点e条边的图

//v为某顶点

void DFSTraverse(int v);//深度优先遍历

void BFSTraverse(int v);//深度优先遍历

private:

char vertex[maxsize];

int visited[maxsize];

int arc[maxsize][maxsize];

int vertexNum,//顶点个数

arcNum;//边的个数

queen queen;

};

Mgraph::Mgraph(char a[], int n, int e)

{

vertexNum = n, arcNum = e;

int i;

for (i = 0; i < vertexNum; i++)

vertex[i] = a[i];

arc[maxsize][maxsize] = { 0 };//初始化邻接矩阵

visited[vertexNum] = { 0 };

int x,y;

for (i = 0; i < arcNum; i++)

{

cout << “输入边的两个顶点”<<endl;

cin >> x>> y;

arc[x][y] = arc[y][x]=1;

}

for (x = 0; x < vertexNum; x++)

{

for (y = 0; y < vertexNum; y++)

cout << arc[x][y];

cout << endl;

}

}

void Mgraph::DFSTraverse(int v)

{

cout << vertex[v];

visited[v] = 1;

int i;

for (i = 0; i < vertexNum; i++)

{

cout << i;

if (arc[v][i] == 1 && visited[v] == 0)

DFSTraverse(i);

}

}

void Mgraph::BFSTraverse(int v)

{

visited[v] = 1;

queen.enqueen(v);

int top,i;

while (!queen.isempty())

{

top = queen.dequeen();

cout << top;

for (i = 0; i < vertexNum; i++)

{

if (arc[top][i] == 1 && visited[top] == 0)

{

queen.enqueen(i);

visited[i] = 1;

cout << vertex[i];

}

}

}

}

void main()

{

char a[4] = {0,1,2,3};

Mgraph  graph(a, 4, 4);

graph.DFSTraverse(0);

graph.BFSTraverse(0);

}

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/kiwi55/article/details/42242391
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞