广度优先搜索

#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");
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值