当前位置: 首页 > 工具软件 > 泛搜 > 使用案例 >

深搜 广搜

田翔
2023-12-01
#include<stdio.h>
#include<iostream>
#include<queue>
#define maxvertex 100
using namespace std;

//邻接表存储图的遍历——深搜和广搜
struct graph
{
    //起点终点权值
    int vertex[maxvertex];//存顶点
    int arc[maxvertex][maxvertex];//存表(邻接矩阵)
    int vertexnum,arcnum;//顶点数和边数
};

int visited[maxvertex];
void createGreaph(graph *g)
{
    int i,j;
    cin>>g->arcnum>>g->vertexnum;//输入边数和顶点数
    for(i=0;i<g->vertexnum;i++)
    {
        cin>>g->vertex[i];//输入每个顶点的值
    }
    for(i=0;i<g->vertexnum;i++)
        for(j=0;j<g->vertexnum;j++)
            g->arc[i][j]=0;
    for(i=1;i<=g->arcnum;i++)
    {//输入边的起点终点权值
        int start,end,weight;
        cin>>start>>end>>weight;
        g->arc[start-1][end-1]=weight;
        g->arc[end-1][start-1]=weight;
    }
}

void BFS(graph *g,int v)
{
	queue<int> q;
	int x,j;
	if(!visited[v])
	{
		cout<<g->vertex[v]<<" ";
		visited[v]=1;
		q.push(v);
	}
	while(!q.empty())
	{
		x=q.front();
		q.pop();
		for(j=0;j<g->vertexnum;j++)
		{
			if(g->arc[x][j] && !visited[j])
			{//x有到j的边并且这条边没有被访问过
				cout<<g->vertex[j]<<" ";
				visited[j]=1;
				q.push(j);//被访问过的顶点继续入队
			}
		}
	}
}

void DFS(graph *g,int v)
{
	int j;
	if(!visited[v])
	{
		cout<<g->vertex[v]<<" ";
		visited[v]=1;//标记为已被访问过
	}
	for(j=0;j<g->vertexnum;j++)
	{
		if(g->arc[v][j] && !visited[j])
		{
			DFS(g,j);
		}
	}
}

void print(graph *g)
{
	int i,j;
	for(i=0;i<g->vertexnum;i++)
	{
		for(j=0;j<g->vertexnum;j++)
			cout<<g->arc[i][j]<<" ";
		cout<<endl;
	}
}


int main()
{
	graph *g;
	memset(visited,0,sizeof(visited));
	g=(graph *)malloc(sizeof(graph));
	createGreaph(g);
	cout<<"输出邻接矩阵:"<<endl;
	print(g);
	cout<<"深度优先搜索:";
	DFS(g,0);
	cout<<endl;
	memset(visited,0,sizeof(visited));

	cout<<"广度优先搜索:";
	BFS(g,0);
	cout<<endl;
    return 0;
}

 类似资料: