[英]The program is aborting with unexpected output, counting unreachable nodes in graph
我剛剛實現了一個 dfs 算法,並想嘗試一個問題。 問題如下:
輸入格式
第一行由 2 個整數 N 和 M 組成,表示該圖中的節點和邊的數量。 接下來的 M 行由 2 個整數 a 和 b 組成,表示節點 a 和 b 之間的無向邊。 下一行由一個整數 x 組成,表示頭節點的索引。
輸出格式:
您需要打印一個整數,表示從給定的頭節點無法訪問的節點數。
測試用例輸入如下:
10 10
8 1
8 3
7 4
7 5
2 6
10 7
2 8
10 9
2 10
5 10
2
這種情況下的輸出是:
0
我寫的代碼:
#include<iostream>
#include<list>
#include<queue>
using namespace std;
int mycount = 0;
//Adj List Implementation for Integer Nodes
class Graph {
private:
int V;
//Array of Linked Lists of size V, V LL's are there
list<int>* adjList;
int* visited;
public:
Graph(int v) {
V = v;
adjList = new list<int>[V];
visited = new int[V] { 0 };
}
void addEdge(int u, int v, bool bidir = true)
{
adjList[u].push_back(v);
if (bidir) {
adjList[v].push_back(u);
}
}
int dfs(int vertex)
{
visited[vertex] = true;
mycount++;
for (auto node : adjList[vertex]) {
if (!visited[node]) {
dfs(node);
}
}
return mycount;
}
};
int main() {
//taking input of number of nodes and edges
int inputNode, inputEdge;
cin >> inputNode >> inputEdge;
//graph object
Graph g(inputNode);
//taking input
for (int i = 0; i < inputEdge; i++) {
int u, v;
cin >> u >> v;
g.addEdge(u, v);
}
int index;
cin >> index;
//run the dfs on index
int reachabeNodes = g.dfs(index);
cout << inputNode - reachabeNodes;
return 0;
}
在我的代碼沒有執行后我看到了其他代碼,但發現它們使用的邏輯與我的幾乎相同,
您應該使用列表向量,而不是指向列表數組的指針,以及向量而不是數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.