赞
踩
由于图的结构比较复杂,任意两个节点之间都可能存在关系,所以不能依靠数据元素在存储区中的物理位置来表示元素之间的关系,即图没有顺序存储结构,但可以依靠邻接矩阵表示法,以及链式存储法,应对不同的需求选择不同的存储结构。
深度优先和广度优先遍历的C++实现如下:
- #include<iostream>
- #include<queue>
- using namespace std;
- typedef struct Point {
- int index;
- struct Point* next;
- }Point,*PT;
- typedef struct Graph {
- PT* nodes;
- int vn, en;
- bool* visit;
- }Graph,*G;
- void GraphInit(G& graph) {
- graph = new Graph;
- cout << "节点数量:";
- cin >> graph->vn;
- graph->nodes = new PT[graph->vn];
- graph->visit = new bool[graph->vn];
- int num;
- int node;
- for (int i = 0; i < graph->vn; i++) {
- graph->visit[i] = false;
- cout << "节点" << i + 1 << "邻居有几个?" << endl;
- cin >> num;
- graph->nodes[i] = new Point;
- graph->nodes[i]->index = i + 1;
- graph->nodes[i]->next = NULL;
- for (int j = 0; j < num; j++) {
- cout << "第" << j + 1 << "邻居为:";
- cin >> node;
- PT newNode = new Point;
- newNode->next = graph->nodes[i]->next;
- graph->nodes[i]->next = newNode;
- newNode->index = node;
- }
- }
- }
- void GraphShow(G graph) {
- for (int i = 0; i < graph->vn; i++) {
- PT p = graph->nodes[i];
- while (p) {
- cout << p->index << " ";
- p = p->next;
- }
- cout << endl;
- }
- }
- void DFS(G graph,int v=0) {
- cout << graph->nodes[v]->index<<" ";
- graph->visit[v] = true;
- PT p = graph->nodes[v];
- while (p->next) {
- if (!graph->visit[p->next->index-1])
- DFS(graph, p->next->index - 1);
- p = p->next;
- }
- }
- void BFS(G graph,int v=0) {
- for (int i = 0; i < graph->vn; i++)
- graph->visit[i] = false;
- queue<int>* qeu = new queue<int>;
- qeu->push(0);
- while (!qeu->empty()) {
- int pn = qeu->front();
- qeu->pop();
- cout << pn+1 << " ";
- graph->visit[pn] = true;
- PT p = graph->nodes[pn];
- while (p && p->next) {
- p = p->next;
- if (!graph->visit[p->index - 1]) {
- qeu->push(p->index - 1);
- graph->visit[p->index - 1] = true;
- }
- }
- }
- }
- int main(void) {
- //测试数据
- /*5
- 2
- 3
- 5
- 1
- 5
- 3
- 1
- 4
- 5
- 2
- 3
- 5
- 4
- 1
- 2
- 3
- 4*/
- //结果
- //1 5 3
- //2 5
- //3 5 4 1
- //4 5 3
- //5 4 3 2 1
- G g;
- GraphInit(g);
- GraphShow(g);
- cout << "深度优先遍历序列为:";
- DFS(g);
- cout << endl << "广度优先遍历序列为:";
- BFS(g);
- //1 5 4 3 2
- //1 5 3 4 2
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。