图的DFS和BFS(C/C++)

 

/* text data */
/* 输入 */
10 10 0    // 节点数、边数、源点
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
0 9
/* 输出 */
0 1 2 3 4 5 6 7 8 9 
0 1 9 2 8 3 7 4 6 5
#include <iostream>
#include <vector>
#include <deque>
/**
 * 图的深度优先搜索和广度优先搜索
 * 存储结构:邻接矩阵
 * 图的特点:无权图、无向图
 **/

std::vector<std::vector<int>> buildGraph(int, int);
void DFS(const std::vector<std::vector<int>> &, int, bool []);
void BFS(const std::vector<std::vector<int>> &, int, bool []);
int main()
{
    int vertexNum, edgeNum, vertex;
    std::cin >> vertexNum >> edgeNum >> vertex;
    std::vector<std::vector<int>> graph {buildGraph(vertexNum, edgeNum)};

    bool visited[vertexNum] {false};
    DFS(graph, vertex, visited);
    std::cout << "\n";
    for (bool &c : visited)
        c = false;
    BFS(graph, vertex, visited);
}
/* build graph */
std::vector<std::vector<int>> buildGraph(int vertexNum, int edgeNum)
{
    std::vector<std::vector<int>> graph(vertexNum, std::vector<int>(vertexNum));
    for (int v1, v2, weight, i = 0; i != edgeNum; ++i)
    {
        std::cin >> v1 >> v2 >> weight;
        graph[v1][v2] = weight;
        graph[v2][v1] = weight;
    }
    return std::move(graph);
}
/* DFS */
void DFS(const std::vector<std::vector<int>> &graph, int vertex, bool visited[])
{
    visited[vertex] = true;
    std::cout << vertex << " ";
    for (unsigned int i = 0; i != graph.size(); ++i)
        if (graph[vertex][i] && !visited[i])
                DFS(graph, i, visited);
}
/* BFS */
void BFS(const std::vector<std::vector<int>> &graph, int vertex, bool visited[])
{
    std::deque<int> Queue;
    visited[vertex] = true;
    Queue.push_back(vertex);
    while (!Queue.empty())
    {
        vertex = Queue.front();
        std::cout << vertex << " ";
        Queue.pop_front();
        for (unsigned int i = 0; i != graph.size(); ++i)
            if (graph[vertex][i] && !visited[i])
            {
                visited[i] = true;
                Queue.push_back(i);
            }
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值