1代码
1.1创建图的邻阶矩阵
void CreateMGraph(MGraph &g, int n, int e)
{
int x,y;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
g.edges[i][j] = 0;
}
}
for(int i=0;i<e;i++){
cin>>x>>y;
g.edges[x][y] = 1;
g.edges[y][x] = 1;
}
g.n=n;
}
1.2以邻接矩阵为存储结构遍历算法
深度优先遍历
void DFS(MGraph g, int v)
{
static int n = 0;
int j;
if (!visited[v]) {
if (!n) {
cout << v;
n++;
}
else
cout << ' ' << v;
visited[v] = 1;
}
for (j = 1; j <= g.n; j++) {
if (!visited[j] && g.edges[v][j] == 1)
DFS(g, j);
}
}
广度优先遍历
void BFS(MGraph g, int v)
{
int i, j, x, n = 0;
queue<int>q;
if (!visited[v]) {
cout << v;
visited[v] = 1;
q.push(v);
}
while (!q.empty()) {
x = q.front();
q.pop();
for (j = 1; j <= g.n; j++) {
if (g.edges[x][j] && !visited[j]) {
cout << ' ' << j;
visited[j] = 1;
q.push(j);
}
}
}
}
2完整代码
#define MAXV 20
#include <stdio.h>
#include <stdlib.h>
#include<queue>
#include <iostream>
using namespace std;
typedef struct
{
int edges[MAXV][MAXV];
int n, e;
} MGraph;
int visited[100];
int flag = 0;
void DFS(MGraph g, int v);
void BFS(MGraph g, int v);
void CreateMGraph(MGraph &g, int n, int e);
int main()
{
MGraph g;
int n, e, i, v;
cin >> n >> e;
CreateMGraph(g, n, e);
cin >> v;
if (n >= 1 && n <= g.n)
{
for (i = 1; i <= g.n; i++) visited[i] = 0;
cout << "dfs:";
DFS(g, v);
cout << endl;
for (i = 1; i <= g.n; i++) visited[i] = 0;
cout << "bfs:";
BFS(g, v);
}
system("pause");
return 0;
}
void CreateMGraph(MGraph &g, int n, int e)
{
int x,y;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
g.edges[i][j] = 0;
}
}
for(int i=0;i<e;i++){
cin>>x>>y;
g.edges[x][y] = 1;
g.edges[y][x] = 1;
}
g.n=n;
}
void DFS(MGraph g, int v)
{
static int n = 0;
int j;
if (!visited[v]) {
if (!n) {
cout << v;
n++;
}
else
cout << ' ' << v;
visited[v] = 1;
}
for (j = 1; j <= g.n; j++) {
if (!visited[j] && g.edges[v][j] == 1)
DFS(g, j);
}
}
void BFS(MGraph g, int v)
{
int i, j, x, n = 0;
queue<int>q;
if (!visited[v]) {
cout << v;
visited[v] = 1;
q.push(v);
}
while (!q.empty()) {
x = q.front();
q.pop();
for (j = 1; j <= g.n; j++) {
if (g.edges[x][j] && !visited[j]) {
cout << ' ' << j;
visited[j] = 1;
q.push(j);
}
}
}
}
3运行结果
