深度优先搜索

深度优先搜索(DFS)

一、使用到的知识点

1、使用堆栈(最后一个顶点最先可以得到)

stack<int> gStack:创建一个堆类
gStack.push(0):压入一个int类型数据
gStack.size() > 0:返回堆的空间
gStack.pop():删除一个堆中的数据
gStack.top():得到堆中最后压入的数据

2、邻接矩阵

矩阵中对于相邻的两点置为1,不相邻的两点为0

3、指针数组

用于存放一系列指向顶点的指针

二、重要函数

1、getNextUnvisitedVertex(int v)

给一个点得到下一个没有访问过的点,若没有则返回-1

2、showVertex(int t)

显示出对应的顶点

3、DFS()

#include "pch.h"
#include <iostream>
#include <stack>
using namespace std;

#define MAX_VERTS 20

class Vertex {
public:
	Vertex(char lab) {
		label = lab;
		wasVisited = false;
	}
	char label;
	bool wasVisited;
};

class Graph {
	Vertex* vertexList[MAX_VERTS];
	int nVerts;
	int adjMat[MAX_VERTS][MAX_VERTS];
	int getNextUnvisitedVertex(int v) {
		for (int i = 0; i < nVerts; i++) {
			if (adjMat[v][i] == 1 && vertexList[i]->wasVisited == false) {
				return i;
			}
		}
		return -1;
	}
public:
	Graph() {
		nVerts = 0;
		for (int i = 0; i < MAX_VERTS; i++) {
			for (int j = 0; j < MAX_VERTS; j++) {
				adjMat[i][j] = 0;
			}
		}
	}
	~Graph() {
		for (int i = 0; i < nVerts; i++) {
			delete vertexList[i];
		}
	}
	void addVertex(char lab) {
		vertexList[nVerts++] = new Vertex(lab);
		nVerts++;
	}
	void addEdge(int start, int end) {
		adjMat[start][end] = 1;
		adjMat[end][start] = 1;
	}
	void printMat() {
		for (int i = 0; i < nVerts; i++) {
			for (int j = 0; j < nVerts; j++) {
				cout << adjMat[i][j] << " " ;
			}
			cout << endl;
		}
	}
	void showVertex(int t) {
		cout << vertexList[t]->label << ' ';
	}
	void DFS() {
		stack<int> gStack;
		vertexList[0]->wasVisited = true;
		showVertex(0);
		gStack.push(0);
		int v;
		while (gStack.size() > 0) {
			v = getNextUnvisitedVertex(gStack.top());
			if (v == -1) {
				gStack.pop();
			}
			else {
				vertexList[v]->wasVisited = true;
				showVertex(v);
				gStack.push(v);
			}
		}
		for (int i = 0; i < nVerts; i++) {
			vertexList[i]->wasVisited = false;
		}
	}
};

int main()
{
	Graph g;
	g.addVertex('A');//0
	g.addVertex('B');//1
	g.addVertex('C');//2
	g.addVertex('D');//3
	g.addVertex('E');//4
	g.addEdge(0, 1);
	g.addEdge(0, 3);
	g.addEdge(1, 0);
	g.addEdge(1, 4);
	g.addEdge(2, 4);
	g.addEdge(3, 0);
	g.addEdge(3, 4);
	g.addEdge(4, 1);
	g.addEdge(4, 2);
	g.addEdge(4, 3);
	g.printMat();
	system("pause");//
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值