代码样板-深度优先搜索-邻接矩阵-无向图-无权值

#include<iostream>
using namespace std;
const int N = 1000;
int n,g[N][N];//n 记住顶点的数量 ; g[N][N]矩阵的元素自动自动初始化为0; 
bool visited[N];  //记住已经访问过的顶点 
void dfs(int x){
	cout<<x<<" ";
	visited[x]=true;   //x号顶点访问过了 
	for (int i=1;i<=n;i++)
		if (g[x][i]==1&&!visited[i])
			dfs(i);   //找到新的,未访问过的顶点 
}
int main(){
	//用邻接矩阵存储无向图
	int e; 
	cin>>n>>e;//n 是顶点的数量,e是边的数量 
	for (int i=0;i<e;i++){  //读入e条边 
		int x, y;
		cin>>x>>y;   //x,y是一条边的两个顶点 
		g[x][y]=g[y][x]=1;   //无向图 
	}
	//深搜
	for (int i=1;i<=n;i++)   //注:图可能是非连通图,可能存在孤岛 
		if (!visited[i]) dfs(i); //注:这里的第一个元素编号为1,存入visited[1],以此类推
	
	return 0;
}

最基础的算法,如果要应用需添加条件


R6-2 邻接矩阵存储图的深度优先遍历

试实现邻接矩阵存储图的深度优先遍历。

函数接口定义:

void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) );

其中MGraph是邻接矩阵存储的图,定义如下:

typedef struct GNode *PtrToGNode;
struct GNode{
    int Nv;  /* 顶点数 */
    int Ne;  /* 边数   */
    WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
};
typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */

函数DFS应从第V个顶点出发递归地深度优先遍历图Graph,遍历时用裁判定义的函数Visit访问每个顶点。当访问邻接点时,要求按序号递增的顺序。题目保证V是图中的合法顶点。

裁判测试程序样例:

#include <stdio.h> typedef enum {false, true} bool; #define MaxVertexNum 10 /* 最大顶点数设为10 */ #define INFINITY 65535 /* ∞设为双字节无符号整数的最大值65535*/ typedef int Vertex; /* 用顶点下标表示顶点,为整型 */ typedef int WeightType; /* 边的权值设为整型 */ typedef struct GNode *PtrToGNode; struct GNode{ int Nv; /* 顶点数 */ int Ne; /* 边数 */ WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */ }; typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */ bool Visited[MaxVertexNum]; /* 顶点的访问标记 */ MGraph CreateGraph(); /* 创建图并且将Visited初始化为false;裁判实现,细节不表 */ void Visit( Vertex V ) { printf(" %d", V); } void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) ); int main() { MGraph G; Vertex V; G = CreateGraph(); scanf("%d", &V); printf("DFS from %d:", V); DFS(G, V, Visit); return 0; } /* 你的代码将被嵌在这里 */

输入样例:给定图如下

5

输出样例:

DFS from 5: 5 1 3 0 2 4 6

 

void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) )
{
    Visit(V);
    Visited[V]=true;
    for(int i=0;i<Graph->Nv;i++)
    {
        if(Graph->G[V][i]==1&&Visited[i]==false)
        {
            DFS(Graph,i,Visit);
        }
    }
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

H._

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值