图的邻接表结构的宽度搜索

#include
#include
using namespace std;

const int MAXN = 100;

struct node
{
	int v;
	struct node *next;
};
typedef struct node *link;

struct Graph
{
	int V;
	int E;
	link *adj;
};
struct Graph *G;
bool visited[MAXN];

void GraphInit(int V, int E)
{
	G = (struct Graph *)malloc(sizeof(struct Graph));
	G->adj = (link *)malloc(sizeof(link)*(V+1));
	G->V = V;
	G->E = E;

	for(int v=1;v<=V;v++)
	{
		G->adj[v] = NULL;
	}
}

void AddEdge(int u, int v)
{
	link e = (link)malloc(sizeof(link));
	e->v = v;
	e->next = G->adj[u];
	G->adj[u] = e;

	link p = (link)malloc(sizeof(link));
	p->v = u;
	p->next = G->adj[v];
	G->adj[v] = p;
}

void BFS(int t)
{
	queue Q;
	Q.push(t);
	visited[t] = true;
	while( !Q.empty() )
	{
		int u = Q.front();
		Q.pop();
		cout << u << " " ;
		link p = G->adj[u];/*此处必须是p=G->adj[u].因为添加边时时G->adj[u] = e 所以遍历的时候p=G->adj[u]*/
		while(p && visited[p->v]==false)
		{
			visited[p->v] = true;
			Q.push(p->v);
			p = p->next;
		}
	}
}

void GraphBFS()
{
	memset( visited, false, sizeof(visited) );
	for(int v=1; v<=G->V; v++)
	{
		if( !visited[v] )
			BFS(v);
	}
}

int main()
{
	int V, E;
	cin >> V >> E;
	GraphInit(V, E);
	int u, v;
	for(int i=0; i> u >> v;
		AddEdge(u, v);
	}
	
	GraphBFS();
	return 0;
}


你可能感兴趣的:(postgraduate,entrance,examinat)