您的位置:首页 > 其它

无向图邻接矩阵以及深度优先遍历.(beta)

2016-01-03 00:00 337 查看
摘要: 写的很乱。。本来就没思路.

#include <iostream>
#include <type_traits>

namespace{
enum Color:int{
white=0;
gray=1;
black=2;
};
}
template<typename T>
struct Node{
T key; //结点的值.
Color color;

template<typename U, class=typename std::enable_if< std::is_same<T, U>::value, void >::type >
Node(const U& k);
};

template<typename T>
template<typename U>
Node<T>::Node(const U& k)
:key(k),
color(::white)
{
//
}

template<typename T>
struct Edge{
Node<T>* start;
Node<T>* end;

template<typename U, class=typename std::enable_if< std::is_same<T, U>::value, void >::type >
Edge(const U& s, const U& e);
};

template<typename T>
template<typename U, class>
Edge<T>::Edge(const U& s, const U& e)
:start(new Node<U>(s)),
end(new Node<U>(e))
{
//
}

template<typename Ty>
class Graph{
private:
unsigned int edgeNumber; //边数.
unsigned int matrix[edgeNumber][edgeNumber]; //矩阵.
Edge<Ty>* edgeArray[edgeNumber]; //存储边.
unsigned int visited[edgeNumber];

template<typename Type, class=typename std::enable_if< std::is_same<Ty, Type>::value, void >::type >
void addSingleEdge(const Type& start, const Type& end);

public:
template<typename Type, class=typename std::enable_if< std::is_integral<Type>::value, void >::type > //这里判断给定number时候是一个数字不然就是错误的.
Graph(const Type& number); //边的条数.

template<typename Type, unsigned int N, class=typename std::enable_if< std::is_same<Ty, Type>::value, void >::type >
Graph(const Type (&array)
[2]);

template<typename Type, class=typename std::enable_if< std::is_same<Ty, Type>::value, void >::type >
void DFS(const Type& a);  //深度优先搜索.
~Graph();

};

template<typename Ty>
template<typename Type, class>
Graph<Ty>::Graph(const Type& number)
:nodeNumber(number),
nodeArray(new Edge<Type>[number])
{
for(int i =0; i<number; ++i){
for(int j=0; j<number; ++j){
this->matrix[i][j]=0;
}
}
std::cout<<"success"<<std::endl;
}

template<typename Ty>
template<typename Type, unsigned int N, class>
Graph<Type>::Graph(const Type (&array)
[2])
:Graph(N)
{
//
for(int i=0; i<N; ++i){ //初始化edgeArray, 并且初始化邻接的矩阵.
this->edgeArray(array[i][0], array[i][1]);
this->addSingleEdge(arry[i][0], array[i][1]);
this->visited[i]=0;
}

}

template<typename Ty>
template<typename Type, class>
void Graph<Ty>::addSingleEdge(const Type& start, const Type& end)
{
this->matrix[start][end]=1;
this->matrix[end][start]=1;
}

template<typename Ty>
template<typename Type, class>
void Graph<Ty>::DFS(const Type& a)
{
if(this->visited[a] != 0){
this->visited[a] =1;
}

for(int i=0; i<this->edgeNumber; ++i){
if(this->matrix[a][j] != 0 && this->visited[j] !=0){
this->DFS(j);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: