我的dfs和bfs算法实现出错

问题描述 投票:0回答:1

我正在尝试用 C++ 编写 dfs 算法。但是当我尝试评估我的代码时,似乎算法未通过某些测试用例。

我的代码有逻辑错误吗?

输入说明: n = 顶点数,m = 边数,v = 起始顶点

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void dfs(vector <int> graph[], int vertex, bool marked[]){
    cout << vertex << endl;
    marked[vertex] = true;
    for(int neighbor:graph[vertex]){
        if(!marked[neighbor]){
            dfs(graph, neighbor, marked);
        }
    }
}

int main(){
    std::ios_base::sync_with_stdio (false);
    cin.tie(NULL);
    
    int n, m, r;
    cin >> n >> m >> r;
    
    vector <int> graph[n+1];
    int tmp1, tmp2;
    for(int i = 0 ; i<m; i++){
        cin >> tmp1 >> tmp2;
        graph[tmp1].push_back(tmp2);
        graph[tmp2].push_back(tmp1);
    }
    
    bool marked[n+1];
    for(int i = 1; i<=n; i++){
        sort(graph[i].begin(), graph[i].end());
        marked[i] = false;
    }
    
    dfs(graph, r, marked);
    
    for(int i = 1; i<=n; i++){
        if (!marked[i]){
            cout << 0 << endl;
        }
    }
    
    return 0;
}
c++ charts depth-first-search breadth-first-search
1个回答
0
投票

编写矢量图[n+1],您已经创建了一个 std::vector 类型的 n+1 个元素的数组。将[]改为()

© www.soinside.com 2019 - 2024. All rights reserved.