图的遍历(递归非递归方法)
#include<iostream>
#include<stdio.h>
#include<stack>
#include<queue>
using namespace std;
typedef char VertexType;
typedef int EdgeType;
#define MAXVEX 100
#define INF 65535
bool visited[MAXVEX] ;
typedef struct Graph
{
VertexType vexs[MAXVEX];
EdgeType arc[MAXVEX][MAXVEX];
int vexnum, arcnum;
}MGraph;
void CreateGraph(MGraph* Graph)
{
cout << "请输入顶点数和边数:"<<endl;
cin >> Graph->vexnum >> Graph->arcnum;
cout << "请输入顶点" << endl;
for (int i = 0; i < Graph->vexnum; i++)
{
cin >> Graph->vexs[i];
}
for (int i = 0; i < Graph->vexnum; i++)
{
for (int j = 0; j < Graph->vexnum; j++)
{
Graph->arc[i][j] = INF;
}
}
cout << "请输入边:" << endl;
for (int i = 0; i < Graph->arcnum; i++)
{
int x, y, v;
cin >> x >> y >> v;
Graph->arc[x][y] = v;
Graph->arc[y][x] = v;
}
}
void print_graph(MGraph* G)
{
for (int i = 0; i < G->vexnum; i++)
{
for (int j = 0; j < G->vexnum; j++)
{
cout << G->arc[i][j] << "\t";
}
cout << "\n";
}
}
void DFS(const MGraph* G, int i)
{
visited[i] = true;
cout << i << "\t";
for (int j = 0; j < G->vexnum; j++)
{
if (!visited[j] && G->arc[i][j] != INF )
{
DFS(G, j);
}
}
}
void DFS01(const MGraph* G, int i)
{
visited[i] = true;
stack<int> s;
s.push(i);
while (!s.empty())
{
i = s.top();
s.pop();
cout << i << "\t";
for (int j = 0; j < G->vexnum; j++)
{
if (!visited[j] && G->arc[i][j] != INF)
{
visited[j] = true;
s.push(j);
}
}
}
}
void BFS(const MGraph* G, int i)
{
queue<int> Q;
Q.push(i);
visited[i] = true;
while (!Q.empty())
{
i = Q.front();
Q.pop();
cout << i << "\t";
for (int j = 0; j < G->vexnum; j++)
{
if (!visited[j] && G->arc[i][j] != INF)
{
visited[j] = true;
Q.push(j);
}
}
}
}
int main()
{
MGraph* G = new MGraph;
CreateGraph(G);
print_graph(G);
BFS(G, 0);
}