数据结构有向图笔记C++

仅个人学习整理,用于复习使用

内容包括有向图的定义,深搜,广搜以及使用广搜求最短路径,拓扑排序

除了拓扑排序,有向图的其他几个方法与无向图相同,只是在插入排序时不需要对称插入数据


#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#define MaxVertexNum 100   //顶点数最大值

typedef char VertexType;  //顶点对应数据类型

typedef int EdgeType;  //边对应数据类型


//有向图的结构体和无向图一样
typedef struct {
	VertexType vex[MaxVertexNum];

	EdgeType edge[MaxVertexNum][MaxVertexNum];

	int vexnum, arcnum;
	//定义顶点表和边表(邻接矩阵),当前顶点数目和边数
}MGraph;

// 初始化图
void InitGraph(MGraph& G) {
    G.vexnum = 0;
    G.arcnum = 0;
    for (int i = 0; i < MaxVertexNum; ++i) {
        for (int j = 0; j < MaxVertexNum; ++j) {
            G.edge[i][j] = 0; // 初始化边为0
        }
    }
}

// 插入顶点
bool InsertVertex(MGraph& G, VertexType v) {
    if (G.vexnum >= MaxVertexNum) {
        cout << "顶点数目达到最大" << endl;
        return false;
    }

    G.vex[G.vexnum] = v;
    G.vexnum++;
    return true;
}

// 插入边
bool InsertEdge(MGraph& G, VertexType v1, VertexType v2, EdgeType weight) {
    int pos1 = -1, pos2 = -1;

    // 查找顶点的索引
    for (int i = 0; i < G.vexnum; ++i) {
        if (G.vex[i] == v1) pos1 = i;
        if (G.vex[i] == v2) pos2 = i;
    }

    // 检查是否找到了顶点
    if (pos1 == -1 || pos2 == -1) {
        cout << "Error: One or both vertices not found." << endl;
        return false;
    }

    // 检查边是否已经存在
    if (G.edge[pos1][pos2] != 0) {
        cout << "Error: Edge already exists." << endl;
        return false;
    }

    // 插入边
    G.edge[pos1][pos2] = weight;

    // 更新边的计数
    G.arcnum++;
    return true;
}

//打印图的邻接矩阵
void printGraph(MGraph G) {
    // 打印图的邻接矩阵
    cout << " 图的邻接矩阵为:" << endl;
    for (int i = 0; i < G.vexnum; ++i) {
        for (int j = 0; j < G.vexnum; ++j) {
            cout << G.edge[i][j] << " ";
        }
        cout << endl;
    }
}


// 广度优先遍历算法  时间复杂度o(v+e)  空间 o(v)
void BFS(MGraph G, VertexType start) {
    //遍历图中的顶点,找到 start 对应的索引 startIndex。
    //如果未找到,输出错误信息并返回。
    int startIndex = -1;
    for (int i = 0; i < G.vexnum; ++i) {
        if (G.vex[i] == start) {
            startIndex = i;
            break;
        }
    }
    if (startIndex == -1) {
        cout << "图中没有该结点" << endl;
        return;
    }

    bool visited[MaxVertexNum];
    memset(visited, 0, sizeof(visited)); // 初始化所有顶点未被访问

    //加入队列,标记为已访问
    queue<int> q;
    q.push(startIndex);
    visited[startIndex] = true;

    cout << "广度优先遍历顺序:" << endl;
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        cout << G.vex[v] << " ";

        for (int i = 0; i < G.vexnum; ++i) {
            if (G.edge[v][i] != 0 && !visited[i]) {
                q.push(i);
                visited[i] = true;
            }
        }
    }
    cout << endl;
}


 深度优先遍历算法
void DFS(MGraph G, VertexType start) {
    // 找到 start 对应的索引 startIndex
    int startIndex = -1;
    for (int i = 0; i < G.vexnum; ++i) {
        if (G.vex[i] == start) {
            startIndex = i;
            break;
        }
    }
    if (startIndex == -1) {
        cout << "图中没有该结点" << endl;
        return;
    }

    bool visited[MaxVertexNum];
    memset(visited, 0, sizeof(visited)); // 初始化所有顶点未被访问

    stack<int> s;
    s.push(startIndex);
    visited[startIndex] = true;

    cout << "深度优先遍历顺序:" << endl;
    while (!s.empty()) {
        int v = s.top();
        s.pop();
        cout << G.vex[v] << " ";

        for (int i = G.vexnum - 1; i >= 0; --i) { // 逆序处理邻接矩阵
            if (G.edge[v][i] != 0 && !visited[i]) {
                s.push(i);
                visited[i] = true;
            }
        }
    }
    cout << endl;
}

// 广度优先搜索求最短路径
void BFSShortestPath(MGraph G, VertexType start, VertexType end) {
    //查找是否存在所要求的顶点
    int startIndex = -1, endIndex = -1;
    for (int i = 0; i < G.vexnum; ++i) {
        if (G.vex[i] == start) startIndex = i;
        if (G.vex[i] == end) endIndex = i;
    }
    if (startIndex == -1 || endIndex == -1) {
        cout << "图中没有指定的结点" << endl;
        return;
    }


    vector<int> dist(G.vexnum, -1); // 记录最短路径的长度
    vector<int> prev(G.vexnum, -1); // 记录前驱结点
    queue<int> q;

    dist[startIndex] = 0;
    q.push(startIndex);

    while (!q.empty()) {
        int v = q.front();
        q.pop();

        for (int i = 0; i < G.vexnum; ++i) {
            if (G.edge[v][i] != 0 && dist[i] == -1) { // 发现未访问的邻接点
                dist[i] = dist[v] + 1;
                prev[i] = v;
                q.push(i);
                if (i == endIndex) break; // 如果找到终点,则终止搜索
            }
        }
    }

    if (dist[endIndex] == -1) {
        cout << "从" << start << "到" << end << "没有路径" << endl;
        return;
    }

    // 打印最短路径
    vector<int> path;
    for (int at = endIndex; at != -1; at = prev[at]) {
        path.push_back(at);
    }
    reverse(path.begin(), path.end());

    cout << "从" << start << "到" << end << "的最短路径长度为: " << dist[endIndex] << endl;
    cout << "路径为: ";
    for (int i : path) {
        cout << G.vex[i] << " ";
    }
    cout << endl;
}

//拓扑排序
void TopologicalSortKahn(MGraph G) {
    vector<int> inDegree(G.vexnum, 0);  // 步骤1:计算每个顶点的入度
    for (int i = 0; i < G.vexnum; ++i) {
        for (int j = 0; j < G.vexnum; ++j) {
            if (G.edge[i][j] != 0) {
                inDegree[j]++;    //inDegree[i] 代表顶点 i 的入度
            }
        }
    }

    queue<int> q;  // 步骤2:初始化队列 并将所有入度为0的顶点添加到队列中,将其作为起点
    for (int i = 0; i < G.vexnum; ++i) {
        if (inDegree[i] == 0) {
            q.push(i);
        }
    }

    vector<int> topOrder;  // 步骤3:处理队列  创建一个对象 topOrder,用于存储拓扑排序的结果。这个向量会按拓扑排序的顺序保存顶点。
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        topOrder.push_back(v);

        for (int i = 0; i < G.vexnum; ++i) {
            if (G.edge[v][i] != 0) {
                if (--inDegree[i] == 0) {
                    q.push(i);
                }
            }
        }
    }
 /*     遍历图中所有的顶点 i,检查是否存在从顶点 v 到顶点 i 的边(即 G.edge[v][i] != 0)。
        如果存在这样的边,则 inDegree[i] 表示顶点 i 的入度需要减少,因为顶点 v 已经被处理,不再是 i 的前驱。
        使用 --inDegree[i] 将顶点 i 的入度减少1。
        如果减少后的入度 inDegree[i] 为0,说明顶点 i 现在没有前驱,可以加入队列 q 进行后续处理。
  */

    if (topOrder.size() == G.vexnum) {  // 步骤4:检查结果,如果表中个数等于结点个数,则证明已经全部处理
        cout << "拓扑排序结果: ";
        for (int i : topOrder) {
            cout << G.vex[i] << " ";
        }
        cout << endl;
    }
    else {
        cout << "图中存在环,无法进行拓扑排序。" << endl;
    }
}
int main()
{
    MGraph G;
    InitGraph(G);

    // 插入顶点
    InsertVertex(G, 'A');
    InsertVertex(G, 'B');
    InsertVertex(G, 'C');
    InsertVertex(G, 'D');
    InsertVertex(G, 'E');


    // 插入边
    InsertEdge(G, 'A', 'B', 10);
    InsertEdge(G, 'A', 'D', 20);
    InsertEdge(G, 'B', 'C', 20);
    InsertEdge(G, 'B', 'D', 20);
    InsertEdge(G, 'C', 'E', 20);
    InsertEdge(G, 'D', 'C', 20);
    InsertEdge(G, 'D', 'E', 20);

    TopologicalSortKahn(G);
    //BFS(G, 'A');
    //DFS(G, 'A');
    //BFSShortestPath(G, 'A', 'D');

    //printGraph(G);
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值