#include <iostream>
#include <queue>
using namespace std;
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 BFS(Graph *pGraph,int nBegin)
{
if(pGraph == NULL || nBegin<1 || nBegin>pGraph->nVertex)return;
//队列
queue<int>q;
//标记数组
int *pMark = NULL;
pMark = (int*)malloc(sizeof(int)*pGraph->nVertex);
memset(pMark,0,sizeof(int)*pGraph->nVertex);
//起始顶点入队 标记
q.push(nBegin);
pMark[nBegin-1] = 1;
//处理
while(!q.empty())
{
nBegin = q.front();
cout<<nBegin<<" ";
q.pop();
//遍历
int i;
for(i=0;i<pGraph->nVertex;i++)
{
//找到有关的且未被打印的
if(pGraph->pMatrix[(nBegin-1)*pGraph->nVertex+i] == 1 && pMark[i] == 0)
{
//入队 进行标记
q.push(i+1);
pMark[i] = 1;
}
}
}
cout<<endl;
//释放
free(pMark);
pMark = NULL;
}
int main()
{
Graph *pGraph = CreateGraph();
BFS(pGraph,2);
return 0;
}