码迷,mamicode.com
首页 > 编程语言 > 详细

C++ DFS

时间:2015-04-05 13:17:25      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>
#include "malloc.h"
#include "stdlib.h"

using namespace std;
typedef bool* pbool;
template<class T>
class Graph
{
    public:
        Graph(int vertexNum,int adjNum);
        virtual ~Graph();
        T* vertex;
        bool** adjArr;
        int vertexNum;
        int adjNum;
        void DFSTravse();
        void DFS(int i,bool *flag);
        //void BFSTravse();
        //void BFS();
    protected:
    private:
};

template<class T>
Graph<T>::Graph(int vertexNum,int adjNum):vertexNum(vertexNum),adjNum(adjNum)
{
    vertex = new T[vertexNum];

    adjArr = new pbool[vertexNum];

    for(int i=0;i<vertexNum;i++)
    {
        adjArr[i] = new bool[vertexNum];
    }
}

template<class T>
Graph<T>::~Graph()
{
    delete [] vertex;
    for(int i=0;i<vertexNum;i++)
    {
        delete[] adjArr[i];
    }
    delete[] adjArr;
}

template<class T>
void Graph<T>::DFSTravse()
{
    bool* flag = new bool[vertexNum];

    //initialize flag
    for(int i=0;i<vertexNum;i++)
    {
        flag[i] = false;
    }

    for(int i=0;i<vertexNum;i++)
    {
        if(!flag[i])
        {
            this->DFS(i,flag);
        }
    }

    delete[] flag;
}

template<class T>
void Graph<T>::DFS(int i,bool* flag)
{
    cout<<vertex[i]<<endl;
    flag[i] = true;

    for(int j=0;j<vertexNum;j++)
    {
        if(adjArr[i][j]&&!flag[j])
        {
            DFS(j,flag);
        }
    }
}

int main()
{
    int vertexNum,adjNum;

    cout<<"input vertextNum and adjNum"<<endl;

    cin>>vertexNum>>adjNum;

    Graph<char> * graph = new Graph<char>(vertexNum,adjNum);

    for(int i=0;i<vertexNum;i++)
    {
        cin>>graph->vertex[i];
    }
    system("pause");
    for(int i=0;i<adjNum;i++)
    {
        int x,y;
        cin>>x>>y;
        cin>>graph->adjArr[x][y];
        graph->adjArr[y][x] = graph->adjArr[x][y];
    }

    system("pause");

    graph->DFSTravse();

    system("pause");

    return 0;
}

 

C++ DFS

标签:

原文地址:http://www.cnblogs.com/yayaxxww/p/4393870.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!