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

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

使用邻接矩阵的方法

内容包括无向图的定义,深搜,广搜以及使用广搜求最短路径

#include <iostream>
#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) {
    //定义 pos1 和 pos2: 这两个变量用于存储顶点 v1 和 v2 在邻接矩阵中的索引,
    // 初始值为 -1 表示尚未找到顶点
    int pos1 = -1, pos2 = -1;

    // 查找顶点的索引
    //遍历图中的顶点数组 G.vex,找到 v1 和 v2 的位置,并分别存储在 pos1 和 pos2 中。
    for (int i = 0; i < G.vexnum; ++i) {
        if (G.vex[i] == v1) pos1 = i;
        if (G.vex[i] == v2) pos2 = i;
    }
    //如果 pos1 或 pos2 仍然是 -1,表示至少有一个顶点未找到。输出错误信息并返回 false。
    if (pos1 == -1 || pos2 == -1) {
        cout << "Error: One or both vertices not found." << endl;
        return false;
    }
    //如果 pos1 或 pos2 仍然是 -1,表示至少有一个顶点未找到。输出错误信息并返回 false
    if (G.edge[pos1][pos2] != 0) {
        cout << "Error: Edge already exists." << endl;
        return false;
    }
    // 将边的权重 weight 插入到邻接矩阵中。对于无向图,更新 pos1 到 pos2 和 pos2 到 pos1 的对称位置
    G.edge[pos1][pos2] = weight;
    G.edge[pos2][pos1] = weight; // 因为是无向图,所以对称

    //增加边的计数 G.arcnum,并返回 true 表示操作成功
    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;
}
int main() {
    MGraph G;
    InitGraph(G);

    queue<VertexType> q;
   
    
    // 插入顶点
    InsertVertex(G, 'A');
    InsertVertex(G, 'B');
    InsertVertex(G, 'C');
    InsertVertex(G, 'D');
    InsertVertex(G, 'E');
    

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

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

    //printGraph(G);

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值