Skip to content

Instantly share code, notes, and snippets.

@ivycheung1208
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivycheung1208/fe02d53a80a5684422da to your computer and use it in GitHub Desktop.
Save ivycheung1208/fe02d53a80a5684422da to your computer and use it in GitHub Desktop.
CC150 4.2
/* CC150 4.2
* Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
*/
#include <iostream>
#include <list>
using namespace std;
class Graph {
public:
Graph(int n) : V(n), adj(new list<int>[V]) {}
~Graph() { delete[] adj; }
void addEdge(int v, int w) { adj[v].push_back(w); } // add w to v's adjacent list
bool isConnected(int v1, int v2);
private:
int V; // number of vertices
list<int> *adj; // array of adjacent lists
void DFSUtil(int v, int w, bool visited[]); // DFS starting from v to w
};
void Graph::DFSUtil(int v, int w, bool visited[])
{
visited[v] = true;
if (visited[w])
return;
for (auto it = adj[v].begin(); it != adj[v].end(); ++it) {
if (!visited[*it])
DFSUtil(*it, w, visited);
if (visited[w])
return;
}
}
bool Graph::isConnected(int v1, int v2)
{
bool *visited = new bool[V];
for (int i = 0; i != V; ++i)
visited[i] = false;
DFSUtil(v1, v2, visited);
if (visited[v2])
return true;
else
return false;
}
int main()
{
Graph g(7);
g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3);
g.addEdge(1, 3); g.addEdge(1, 4);
g.addEdge(2, 5);
g.addEdge(3, 2); g.addEdge(3, 5); g.addEdge(3, 6);
g.addEdge(4, 3); g.addEdge(4, 6);
g.addEdge(6, 5);
cout << g.isConnected(0, 2) << endl;
cout << g.isConnected(3, 1) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment