xqn2017

导航

【转载】DFS和BFS

#include <iostream>
#include <stack>
#include <queue>
#include <stdlib.h>
using namespace std;
#define MAX 100

typedef struct
{
	int edges[MAX][MAX];
	int n;
	int e;
}MGraph;

bool visited[MAX] = False;

void CreateMGraph(MGraph &G)
{
	int i,j;
	int s,t;
	int v;
	for(i=0;i<G.n;i++)
	{
		for(j=0;j<G.n;j++)
		{
			G.edges[i][j] =0;
		}
	}
	for(i=0;i<G.e;i++)
	{
		scanf("%d %d %d",&s,&t,&v);
		G.edges[s][t] = v;
	}
		
}
void DFS(MGraph G,int node)
{
	int i;
	printf("%d",node);
	visited[node] = True;
	for(i=0;i<G.n;i++)
	{
		if(G.edges[v][i]!=0&&visited[i]==False)
		{
			DFS(G,i);
		}
	}
	
}

void DFS1(MGraph G,int node)
{
	stack <int> s;
	printf("%d",node);
	visited[node] = True;
	s.push(node);
	while(!s.empty())
	{
		int i,j;
		i = s.top();
		for(j=0;j<G.n;j++)
		{
			if(G.edges[i][j]!=0&&visited[j]==False)
			{
				printf("%d",j);
				visited[j]=True;
				s.push(j);
				break;
			}
		}
		if(j==G.n)
		{
			s.pop();
		}
	}
}

void BFS(MGraph G,int node)
{
	queue <int> q;
	printf("%d",node);
	visited[node] = True;
	q.push(node);
	while(!q.empty())
	{
		int i,j;
		i = q.front();
		q.pop();
		for(j=0;j<G.n;j++)
		{
			if(G.edges[i][j]!=0&&visited[j]==False)
			{
				printf("%d",j);
				visited[j] = True;
				q.push(j);
			}
		}
	}
	
}

  

备注:本文为转载,原文信息如下:

 

作者:海子

    

出处:http://www.cnblogs.com/dolphin0520/

    

本博客中未标明转载的文章归作者海子和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

posted on 2017-12-11 09:43  xqn2017  阅读(2)  评论(0)    收藏  举报