谁能帮忙解读一下我的家教给我的DFS + BFS?

第一个DFS

#include <iostream>
#include <vector>
using namespace std;

void DFS(int v, vector<bool>& visited, const vector<vector<int>>& graph) {
    visited[v] = true;
    cout << v << " ";

    for (int neighbor : graph[v]) {
        if (!visited[neighbor]) {
            DFS(neighbor, visited, graph);
        }
    }
}

int main() {
    vector<vector<int>> graph = {
        {1, 2},   // 0
        {0, 3, 4}, // 1
        {0, 4},   // 2
        {1},      // 3
        {1, 2}    // 4
    };

    vector<bool> visited(graph.size(), false);
    cout << "Depth First Search starting from vertex 0:\n";
    DFS(0, visited, graph);

    return 0;
}

第二个BFS

#include <iostream>
#include <vector>
#include <queue>

void BFS(int start, const std::vector<std::vector<int>>& graph) {
    std::vector<bool> visited(graph.size(), false);
    std::queue<int> queue;

    visited[start] = true;
    queue.push(start);

    while (!queue.empty()) {
        int v = queue.front();
        queue.pop();
        std::cout << v << " ";

        for (int neighbor : graph[v]) {
            if (!visited[neighbor]) {
                visited[neighbor] = true;
                queue.push(neighbor);
            }
        }
    }
}

int main() {
    std::vector<std::vector<int>> graph = {
        {1, 2},   // 0
        {0, 3, 4}, // 1
        {0, 4},   // 2
        {1},      // 3
        {1, 2}    // 4
    };

    std::cout << "Breadth First Search starting from vertex 0:\n";
    BFS(0, graph);

    return 0;
}

(想要原代码+注释)

1 个赞

这是抄网上的吧(你家教)感觉好眼熟

1 个赞

不是

真不是真不是可以教我屏幕截图怎么找到吗

啥屏幕截图

1 个赞

win+shift+s哪个

Sh+Win+s

1 个赞

YES

1 个赞

c本来不应该发的

@徐熙喆 关了