图的深度优先搜索(DFS)

深度优先是指要一条路走到黑,遍历具有后来先服务的特性,适合用递归。

算法步骤:

        1、建立bool类型访问结点标记数组,并初始化所有元素为false,代表每个结点都没有被访问;

        2、以图中的的一个结点为原点v,访问v并在访问标记数组中标记已访问;
        3、遍历v的所有邻接点,若有未访问,递归。

代码实现:

#include <iostream>
using namespace std;
#define maxn 10
bool visited[maxn];
using VexType = char;

class AMGragh
{
public:
    VexType vex[maxn];
    int edge[maxn][maxn];
    int vex_num, edge_num;
};

int LocateVex(const AMGragh& g, const VexType& v)
{
    for (int i = 0; i < g.vex_num; i++)
    {
        if (v == g.vex[i])
        {
            return i;
        }
    }
    return -1;
}

void CreateAMGraph(AMGragh& g)
{
    memset(g.vex, 0, sizeof(g.vex));
    memset(g.edge, 0, sizeof(g.edge));
    VexType u, v;
    int loc_u, loc_v;
    cout << "请输入顶点数:" << endl;
    cin >> g.vex_num;
    cout << "请输入边数:" << endl;
    cin >> g.edge_num;
    cout << "请依次输入结点:" << endl;
    for (int i = 0; i < g.vex_num; i++)
    {
        cin >> g.vex[i];
    }
    cout << "请依次输入边的两个顶点:" << endl;
    for (int i = 0; i < g.edge_num;i++)
    {
        cin >> u >> v;
        loc_u = LocateVex(g, u);
        loc_v = LocateVex(g, v);
        g.edge[loc_u][loc_v] = g.edge[loc_v][loc_u] = 1;
    }
}

//void OutputAMGragh(const AMGragh& g)
//{
//    for (int i = 0; i < g.vex_num; i++)
//    {
//        for (int j = 0; j < g.vex_num; j++)
//        {
//            cout << g.edge[i][j] << " ";
//        }
//        cout << endl;
//    }
//}

void DFS(const AMGragh g, const int& v)
{
    cout << g.vex[v] << " ";
    visited[v] = true;
    for (int i = 0; i < g.vex_num; i++)
    {
        if (g.edge[v][i] && !visited[i])
        {
            DFS(g, i);
        }
    }
}

int main()
{
    VexType start_vex;
    AMGragh g;
    CreateAMGraph(g);
    //OutputAMGragh(g);
    cout << "请输入要开始深度优先遍历的首个结点:" << endl;
    cin >> start_vex;
    int str = LocateVex(g, start_vex);
    DFS(g, str);

    return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可惜浅灰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值