#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
int nVertex;
int nEdge;
int *pMatrix;
}Graph;
Graph *CreateGraph()
{
Graph *pGraph = NULL;
pGraph = (Graph*)malloc(sizeof(Graph));
printf("请输入顶点个数与边的个数:\n");
int nV,nE;
scanf("%d%d",&nV,&nE);
pGraph->nVertex = nV;
pGraph->nEdge = nE;
//矩阵
pGraph->pMatrix = (int*)malloc(sizeof(int)*nV*nV);
memset(pGraph->pMatrix,0,sizeof(int)*nV*nV);
//放入边
int v1,v2;
int i;
for(i=0;i<nE;i++)
{
printf("请输入一条边:\n");
scanf("%d%d",&v1,&v2);
//确保该点符合范围要求,且该点没有被赋值过
if(v1 != v2 && v1>=1 && v1 <= nV && v2>=1 && v2<=nV && pGraph->pMatrix[(v1-1)*nV+v2-1]==0)
{
pGraph->pMatrix[(v1-1)*nV+v2-1] = 1;
pGraph->pMatrix[(v2-1)*nV+v1-1] = 1;
}
else
{
i--;
}
}
return pGraph;
}
void MyDFS(Graph *pGraph,int nBegin,int *pMark)
{
//打印
printf("%d",nBegin);
//标记
pMark[nBegin-1] = 1;
//遍历
int i;
for(i=0;i<pGraph->nVertex;i++)
{
//找到有关且未被处理过的节点
if(pGraph->pMatrix[(nBegin-1)*pGraph->nVertex+i]==1 && pMark[i]==0)
{
//处理
MyDFS(pGraph,i+1,pMark);
}
}
}
void DFS(Graph *pGraph,int nBegin)
{
if(pGraph == NULL || nBegin>pGraph->nVertex)return;
//标记数组
int *pMark = NULL;
pMark = (int*)malloc(sizeof(int)*pGraph->nVertex);
memset(pMark,0,sizeof(int)*pGraph->nVertex);
//处理
MyDFS(pGraph,nBegin,pMark);
//释放
free(pMark);
pMark = NULL;
}
int main()
{
Graph *pGraph = CreateGraph();
int i;
DFS(pGraph,2);
return 0;
}