CareerCup-4.2
Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
开始想用Dijkstra算法,后来发现根本不需要最短只求连通性。回头还得回忆下Dijkstra,写起来有点生疏了。
#include <iostream>
#include <stack>
using namespace std;
#define Data int
class Graph
{
public:
Graph(int size):mSize(size)
{
data = new Data*[size];
for(int i=0; i<size; i++)
{
data[i] = new Data[size];
for(int j=0; j<size; j++)
{
data[i][j] = 0;
}
}
};
void addLink(int src, int dst, int weight=1)
{
data[src][dst] = weight;
};
bool isReached(int src, int dst)
{
if(src == dst) return true;
bool reached[mSize];
for(int i=0; i<mSize; i++)
reached[i] = false;
stack<Data> stack;
stack.push(src);
reached[src] = true;
while(true)
{
Data d = stack.top();
cout<<"Reach: "<<d<<endl;
if(d == dst)
return true;
stack.pop();
for(int i=0; i<mSize; i++)
{
if(data[d][i] > 0 && !reached[i])
stack.push(i);
};
if(stack.empty()) break;
};
return false;
};
private:
int mSize;
Data** data;
};
int main()
{
Graph graph(4);
graph.addLink(0, 3);
graph.addLink(3, 2);
cout<<boolalpha<<graph.isReached(0, 1)<<endl;
system("pause");
}