#include <iostream> #include <queue> using namespace std; //因为只是为了练习DFS和BFS 数据结构定义的很随意 没有优化类啦 能用就行 class Graph { private: static const int MAX=100; int weight[MAX][MAX];//任意一个图最大节点数为MA int nodes; int vertexs; bool *isVisited; public: void init(int n,int v);//init相当于构造函数的功能 ~Graph() { delete []isVisited; } void SearchBfs(int node); void SearchDfs(int node); void visit (int n) { cout<<"->"<<n; } }; void Graph::init (int n,int v)//先后以节点数和边数为形参 { vertexs=v;//节点数和边数初始化 nodes=n; for(int i=0;i!=n;i++) for(int j=0;j!=n;j++) { weight[i][j]=0; } int i=0,j=0,weight_=0; for(int h=0;h!=v;h++) { cout<<" vertex origin to vertex destition and weight "<<endl; cin>>i>>j>>weight_; weight[i][j]=weight_; } isVisited=new bool[nodes];//记录节点是否被遍历 for(int w=0;w!=nodes;) isVisited[w++]=false; } void Graph::SearchDfs(int node) { visit(node); isVisited[node]=true; for(int i=0;i!=nodes;i++) { if(weight[node][i]!=0&&isVisited[i]==false) SearchDfs(i); } } void Graph::SearchBfs(int node) { queue<int>myQueue; myQueue.push(node); visit(node); isVisited[node]=true; while(!myQueue.empty()) { int v=myQueue.front(); myQueue.pop(); for(int i=0;i!=nodes;i++) { if(weight[v][i]!=0&&isVisited[i]==false) { visit(i); isVisited[i]=true; myQueue.push(i); } } } } int main() { Graph myGraph; myGraph.init(9,8); //myGraph.SearchBfs(0); myGraph.SearchDfs(0); }
时间: 2024-10-07 12:50:26