#include <iostream>
#include <stdio.h>
#include <queue>
#include <list>
using namespace std;
typedef struct _stNode
{
int syb;
}stNode;
#define NUM 8
stNode nodeAry[8];
stNode *parent[8];
int dis[8];
int color[8];
list<stNode *> graph[8];
queue<stNode *> nodeQueue;
list<stNode *>::iterator itrList;
stNode *getNode(int i)
{
int j = 0;
for(j = 0; j < NUM; j++)
{
if(nodeAry[j].syb == i)
{
return &nodeAry[j];
}
}
}
int nodeSyb(stNode *node)
{
return node->syb;
}
void createG()
{
int i = 0;
for(i = 0; i < NUM; i++)
{
nodeAry[i].syb = i;
}
graph[0].push_back(&nodeAry[0]);
graph[0].push_back(&nodeAry[1]);
graph[0].push_back(&nodeAry[4]);
graph[1].push_back(&nodeAry[0]);
graph[1].push_back(&nodeAry[5]);
graph[2].push_back(&nodeAry[2]);
graph[2].push_back(&nodeAry[3]);
graph[2].push_back(&nodeAry[5]);
graph[2].push_back(&nodeAry[6]);
graph[3].push_back(&nodeAry[2]);
graph[3].push_back(&nodeAry[6]);
graph[3].push_back(&nodeAry[7]);
graph[4].push_back(&nodeAry[0]);
graph[5].push_back(&nodeAry[2]);
graph[5].push_back(&nodeAry[6]);
graph[6].push_back(&nodeAry[2]);
graph[6].push_back(&nodeAry[3]);
graph[6].push_back(&nodeAry[5]);
graph[6].push_back(&nodeAry[7]);
graph[7].push_back(&nodeAry[3]);
graph[7].push_back(&nodeAry[6]);
}
void bfs(int j)
{
int i = 0;
for(i = 0; i < NUM; i++)
{
dis[i] = -1;
parent[i] = NULL;
color[i] = 0;
}
nodeQueue.push(getNode(j));
color[j] = 1;
dis[j] = 0;
stNode *node;
int pIndex = 0;
int cIndex = 0;
while(1)
{
if(nodeQueue.empty())
{
break;
}
node = nodeQueue.front();
nodeQueue.pop();
pIndex = nodeSyb(node);
for(itrList = graph[pIndex].begin(); itrList != graph[pIndex].end(); ++itrList)
{
cIndex = nodeSyb(*itrList);
if(color[cIndex] == 0)
{
dis[cIndex] = dis[pIndex] + 1;
color[cIndex] = 1;
nodeQueue.push(*itrList);
parent[cIndex] = node;
}
}
color[nodeSyb(node)] = 2;
}
}
int main()
{
createG();
bfs(1);
int i = 0;
for(i = 0; i < NUM; i++)
{
printf("node = %d color = %d dis = %d",
nodeAry[i].syb, color[i], dis[i]);
if(parent[i] != NULL)
{
printf(" parent = %d\n", parent[i]->syb);
}
else
{
printf(" start node\n");
}
}
}
广度优先搜索
最新推荐文章于 2024-10-04 21:58:42 发布