DFS深度优先搜索 算法基础篇(六)
View Code
// DFS算法.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <stack> #include <iostream> using namespace std; #define Max 20 typedef int ElemType; struct Vertex { ElemType V; bool Visit; }; typedef int EdgeType; struct Graphic { Vertex Vex[Max]; EdgeType Edge[Max][Max]; int Arc; int VexNum; }; typedef struct Graphic* Graph; void ReadGraph(Graph G) //读图函数 { int i; int from,to; memset(G->Edge,0,sizeof(G->Edge)); for( i=0;i<Max;i++) { G->Vex[i].V=i; G->Vex[i].Visit=false; } printf("请输入点数和边数: "); scanf("%d%d",&(G->VexNum),&(G->Arc)); for( i=0;i<G->Arc;i++) { printf("请输入第%d条边的起点终点:",i+1); scanf("%d%d",&from,&to); G->Edge[from][to]=1; G->Edge[to][from]=1; } } void DFSStack(Graph G,int next) //栈版本 { stack<Vertex> vStack; vStack.push(G->Vex[next]); Vertex vTemp; while(!vStack.empty()) { vTemp=vStack.top(); vStack.pop(); cout<<"Vex= "<<vTemp.V<<" "; G->Vex[vTemp.V].Visit=true; for(int i=0;i<G->VexNum;i++) { if(G->Edge[vTemp.V][i]==1&&!(G->Vex[i].Visit)) { G->Vex[i].Visit=true; vStack.push(G->Vex[i]); } } } } void DFSRecursive(Graph G,int next) //迭代版本 { int i=0; G->Vex[next].Visit=true; cout<<"Vex= "<<G->Vex[next].V<<" "; for(;i<G->VexNum;i++) { if(G->Edge[G->Vex[next].V][i]==1&&!(G->Vex[i].Visit)) DFSRecursive(G,i); } } int _tmain(int argc, _TCHAR* argv[]) { Graph G=(Graph)malloc(sizeof(struct Graphic)); ReadGraph( G); // DFSRecursive(G,0); DFSStack( G,0); return 0; }