图的深度优先搜索和广度优先搜索

图的遍历

深度优先搜索

/*图的遍历之深度优先搜索*/
void dfs(int v)
{
	visit[v] = 1;
	cout << v << " ";
	for (int j = 0; j < nv; ++j) {
		if (MGraph[v][j] == 1&&visit[j]==0) {
			dfs(j);
		}
	}
}

广度优先搜索

void bfs(int v)
{
	queue<int> q;
	q.push(v);
	visit[v] = 1;
	while (!q.empty()) {
		int u = q.front();
		q.pop();
		cout << u << " ";
		for (int j = 0; j < nv; ++j) {
			if (MGraph[u][j] == 1 && visit[j] == 0) {
				q.push(j);
				visit[j] = 1;
			}
		}
	}
}

Full Code

#include<iostream>
#include<queue>

using namespace std;

#define MAX_VERTEX 100

int MGraph[MAX_VERTEX][MAX_VERTEX];
int visit[MAX_VERTEX];

int nv, ne;
void creatMGraph();
void printMGraph();
void dfs(int v);
void bfs(int v);

int main()
{	
	creatMGraph();
	//printMGraph();
	cout << "请输入遍历起始结点:";
	int v;
	cin >> v;
	/*dfs(v);
	cout << endl;*/
	bfs(v);
	system("pause");
	return 0;
}
void creatMGraph()
{
	cout << "请输入结点数nv: ";
	cin >> nv;
	//初始化
	int i, j;
	for (i = 0; i < nv; ++i) {
		visit[i] = 0;	
	}
	for (i = 0; i < nv; ++i) {
		for (j = 0; j < nv; ++j) {
			MGraph[i][j] = 0;
		}
	}
	//添加边
	cout << "请输入边数ne:";
	cin >> ne;
	cout << "请依次输入边(例如:3 1): " << endl;
	for (int k = 0; k < ne; ++k) {
		cin >> i >> j;
		MGraph[i][j] = 1;
		MGraph[j][i] = 1;
	}
}
void printMGraph()
{
	int i, j;
	for (i = 0; i < nv; ++i) {
		for (j = 0; j < nv; ++j) {
			cout << MGraph[i][j] << " ";
		}
		cout << endl;
	}
}
void dfs(int v)
{
	visit[v] = 1;
	cout << v << " ";
	for (int j = 0; j < nv; ++j) {
		if (MGraph[v][j] == 1&&visit[j]==0) {
			dfs(j);
		}
	}
}
void bfs(int v)
{
	queue<int> q;
	q.push(v);
	while (!q.empty()) {
		int u = q.front();
		q.pop();
		visit[u] = 1;
		cout << u << " ";
		for (int j = 0; j < nv; ++j) {
			if (MGraph[u][j] == 1 && visit[j] == 0) {
				q.push(j);
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值