Connectivity in a directed graph (二)

2014-11-24 01:18:32 · 作者: · 浏览: 7
urn false;
}
delete []visited;
return true;
}

int main(int argc, char* argv[]) {
Graph g1 = Graph(5);
g1.addEdge(0, 1);
g1.addEdge(1, 2);
g1.addEdge(2, 3);
g1.addEdge(3, 0);
g1.addEdge(2, 4);
g1.addEdge(4, 2);
if (g1.isStrongConnected())
cout << "yes" << endl;
else
cout << "non" << endl;
Graph g2(4);
g2.addEdge(0, 1);
g2.addEdge(1, 2);
g2.addEdge(2, 3);
if (g2.isStrongConnected())
cout << "yes" << endl;
else
cout << "non" << endl;
cin.get();
return 0;
}

#include
#include
using namespace std;

class Graph {
int vexNum;
list* adjacents;
public:
Graph(int _vexNum);
~Graph();
void addEdge(int v, int w);
void DFSUtil(int v, bool* visited);
bool isStrongConnected();
};

Graph::Graph(int _vexNum) {
vexNum = _vexNum;
adjacents = new list[vexNum];
}

Graph::~Graph() {
delete []adjacents;
}

void Graph::addEdge(int v, int w) {
adjacents[v].push_back(w);
}

void Graph::DFSUtil(int v, bool* visited) {
visited[v] = true;
list::iterator iter;
for (iter = adjacents[v].begin(); iter != adjacents[v].end(); iter++)
if (false == visited[*iter])
DFSUtil(*iter, visited);
}

bool Graph::isStrongConnected() {
bool* visited = new bool[vexNum];
int v;
for (v = 0; v < vexNum; v++)
visited[v] = false;
DFSUtil(0, visited);
for (v = 0; v < vexNum; v++)
if (false == visited[v]) {
delete []visited;
return false;
}
Graph gt = Graph(vexNum);
list::iterator iter;
for (v = 0; v < vexNum; v++) {
for (iter = adjacents[v].begin(); iter != adjacents[v].end(); iter++)
gt.adjacents[*iter].push_back(v);
}
for (v = 0; v < vexNum; v++)
visited[v] = false;
gt.DFSUtil(0, visited);
for (v = 0; v < vexNum; v++)
if (false == visited[v]) {
delete []visited;
return false;
}
delete []visited;
return true;
}

int main(int argc, char* argv[]) {
Graph g1 = Graph(5);
g1.addEdge(0, 1);
g1.addEdge(1, 2);
g1.addEdge(2, 3);
g1.addEdge(3, 0);
g1.addEdge(2, 4);
g1.addEdge(4, 2);
if (g1.isStrongConnected())
cout << "yes" << endl;
else
cout << "non" << endl;
Graph g2(4);
g2.addEdge(0, 1);
g2.addEdge(1, 2);
g2.addEdge(2, 3);
if (g2.isStrongConnected())
cout << "yes" << endl;
else
cout << "non" << endl;
cin.get();
return 0;
}