【发布时间】:2014-08-06 03:01:29
【问题描述】:
在输入规范中,N 是节点数,M 是边数。所以第一个简单的检查是 M 应该等于 N-1 否则它根本不可能是一棵树。
我接下来所做的只是一个 DFS,在其中我看到在 DFS 期间我们是否再次遇到访问过的节点(与父节点不同,父节点是指调用下一个 dfs 的节点与它相邻的节点)那么这意味着我们有一个循环,它不是一棵树。但显然我的解决方案不断得到错误的答案。我发布了代码,但只发布了重要的 sn-ps。我将图形存储为邻接列表,我发布了函数isTree(),它测试它是否是一棵树?什么是正确的逻辑?
#include <iostream>
#include <list>
using namespace std;
// Graph class represents a directed graph using adjacency list representation
class Graph
{
int V; // No. of vertices
list<int> *adj; // Pointer to an array containing adjacency lists
bool isTreeUtil(int v, bool visited[],int parent);
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // function to add an edge to graph
bool isTree(); // Tells whether the given graph is a tree or not
void printGraph();
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V+1];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
adj[w].push_back(v);
}
bool Graph::isTreeUtil(int v, bool visited[],int parent)
{
//int s_v = v;
visited[v] = true;
list<int>::iterator i;
for(i = adj[v].begin(); i != adj[v].end(); ++i) {
if (!visited[*i])
isTreeUtil(*i,visited,v);
else {
if (*i != parent && visited[*i])
return false;
}
}
return true;
}
bool Graph::isTree() {
bool *visited = new bool[V+1];
for(int i = 1; i < V+1; i++)
visited[i] = false;
visited[1] = true; // marking the first node as visited
for(int i = 1; i < V+1; i++)
visited[i] = false;
int parent = -1; // initially it has no parent
//list<int> :: iterator i;
//for (i = adj[v].begin(); i != adj[v].end(); ++i)
return isTreeUtil(1, visited, parent);
}
void Graph::printGraph() {
for (int i = 1;i <= this->V; i++) {
cout << i << "->";
list<int>::iterator j;
for (j = adj[i].begin(); j != adj[i].end(); ++j) {
cout << *j << "->";
}
cout << "\n";
}
}
int main() {
int N, M;
cin >> N >> M;
Graph G(N);
int v, w;
int m = 0;
while (m < M) {
cin >> v >> w;
G.addEdge(v,w);
m++;
}
if (M != N-1) {
cout << "NO\n";
else if (G.isTree())
cout << "YES\n";
else
cout << "NO\n";
}
【问题讨论】:
-
为什么要投反对票?我把问题写清楚了
-
我没有投反对票(以防万一)
-
您提交的代码要求用户输入以填充图表。这很乏味,您能否提供一些对于 isTree() 得到错误结果的图表示例?
-
@TobyLiu 这就是我在纸上绘制的所有简单测试用例的问题所在,但提交失败时!而且我不知道哪个测试用例失败了。
-
树是图,但任意图不一定是树。
标签: c++ graph tree depth-first-search