Data structure graph algorithm 6.1-6.2 Create undirected network algorithm 6.4-6.6DFS

An unknown college student, known as Caigou in the world of martial arts
original author: jacky Li
Email: [email protected]

Time of completion:2022.12.6
Last edited: 2022.12.6

5fa43ffea1ba4156bd7157e5fdb24ab0.jpeg

Algorithm 6.1-6.2 creates an undirected network

Level 1: Algorithm 6.1 Adjacency Matrix

mission details

The task of this level: write a small program that can output the adjacency matrix of an undirected graph.

related information

In order to complete this task, you need to master: 1. Create an adjacency matrix

Programming requirements

Follow the prompts, add code in the editor on the right, and output the adjacency matrix.

Enter description

The first line is the number of vertices n and the number of edges e, separated by spaces. The second line is n character names of the number of vertices, separated by spaces. The next e lines are the corresponding edges. For example, AB 400 represents vertices A and There is an edge between B with a weight of 400

Test instruction

The platform will test the code you write:

Test input:

4 5

A B C D

A B 100

A C 200

B C 300

B D 400

C D 500

Expected output:

∞ 100 200 ∞

100 ∞ 300 400

200 300 ∞ 500

∞ 400 500 ∞

Reference Code

#include <iostream>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstring>

#define IOS std::ios::sync_with_stdio(false)
//#define YES cout << "1"
//#define NO cout << "0"
#define MaxInt 0x3f
#define MVNum 100
#define OK 1
#define ERROR 0

const int N = 1003;

using namespace std;
typedef long long LL;

typedef struct
{
	char vexs[MVNum];
	int arcs[MVNum][MVNum];
	int vexnum, arcnum;
}AMGraph;

int LocateVex(AMGraph G , char v) //确定点v在G中的位置
{
	for(int i = 1; i <= G.vexnum; i ++)
		if(G.vexs[i] == v)
			return i;
   return -1;
}

int CreateUDN(AMGraph &G)
{
	cin >> G.vexnum >> G.arcnum;
	for(int i = 1; i <= G.vexnum; i ++)
		cin >> G.vexs[i];
		
	for(int i = 1; i <= G.vexnum; i ++)
		for(int j = 1; j <= G.vexnum; j ++)
			G.arcs[i][j] = MaxInt;
			
	char v1, v2; int w;
	
	for(int k = 1; k <= G.arcnum; k ++)
	{
		cin >> v1 >> v2 >> w;
		int i = LocateVex(G, v1), j = LocateVex(G, v2);
		G.arcs[i][j] = w, G.arcs[j][i] = w;
	}
	
	for(int i = 1; i <= G.vexnum; i ++)
	{
		for(int j = 1; j <= G.vexnum; j ++)
			if(G.arcs[i][j] == MaxInt) cout << "∞" << "   ";
			else cout << G.arcs[i][j] << "   ";
		cout << endl;
	}
	return OK;
}

signed main()
{
	IOS; 
	AMGraph G;
	CreateUDN(G);
    return 0;
}

Level 2: Algorithm 6.2 to establish adjacency list

mission details

The task of this level: write a small program that can output the undirected network adjacency list.

related information

In order to complete this task, you need to master: 1. Create an adjacency list

Programming requirements

Follow the prompts, add code in the editor on the right, and output the adjacency list.

Enter description

The first line is the number of vertices n and the number of edges e, separated by spaces. The second line is n character names of the number of vertices, separated by spaces. The next lines e are the corresponding edges. For example, AB represents vertices A and B. There is an edge between

Test instruction

The platform will test the code you write:

Test input:

4 5

A B C D

A B

A C

B C

B D

C D

Expected output:

A->2->1

B->3->2->0

C->3->1->0

D->2->1

Reference Code

#include <iostream>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstring>

#define IOS std::ios::sync_with_stdio(false)
//#define YES cout << "1"
//#define NO cout << "0"
#define MaxInt 0x3f
#define MVNum 100
#define OK 1
#define ERROR -1

const int N = 1003;

using namespace std;
typedef long long LL;

typedef struct ArcNode 
{
	int adjvex;
	struct ArcNode *nextarc;
}AMGraph;

typedef struct VNode
{
	char data;
	ArcNode *firstarc;
}VNode, AdjList[MVNum];

typedef struct
{
	AdjList vertices;
	int vexnum, arcnum;
}ALGraph;

int LocateVex(ALGraph G , char v)
{
	for(int i = 1; i <= G.vexnum; i ++)
		if(G.vertices[i].data == v)
			return i;
   return ERROR;
}

int CreateUDG(ALGraph &G)
{ 
	cin >> G.vexnum >> G.arcnum;
	for(int i = 1; i <= G.vexnum; i ++)
	{
		cin >> G.vertices[i].data;
		G.vertices[i].firstarc = NULL;
	}
	
	char v1, v2;
	
	for(int k = 1; k <= G.arcnum; k ++)
	{
		cin >> v1 >> v2;
		int i = LocateVex(G, v1), j = LocateVex(G, v2);
		
		ArcNode *p1 = new ArcNode;
		p1 -> adjvex = j, p1 -> nextarc = G.vertices[i].firstarc, G.vertices[i].firstarc = p1;
		ArcNode *p2 = new ArcNode;
		p2 -> adjvex = i, p2 -> nextarc = G.vertices[j].firstarc, G.vertices[j].firstarc = p2;
	}
	
	return OK;
}

signed main()
{
	IOS; int i;
	ALGraph G;
	CreateUDG(G);
	
	for(i = 1 ; i <= G.vexnum ; i ++)
	{
		VNode temp = G.vertices[i];
		ArcNode *p = temp.firstarc;
		if(p == NULL)
		{
			cout << G.vertices[i].data;
			cout << endl;
		}
		else
		{
			cout << temp.data;
			while(p)
			{
				cout << "->";
				cout << p->adjvex - 1;
				p = p->nextarc;
			}
		}
		cout << endl;
	}
	return 0;
}

Algorithm 6.4-6.6DFS

Level 1: Algorithm 6.5 uses adjacency matrix to represent deep search of graph

mission details

The task of this level: write a deep search program that uses an adjacency matrix to represent a graph.

related information

In order to complete this task, you need to master: 1. How to create an adjacency matrix 2. How to perform a deep search on a graph.

Programming requirements

According to the prompts, add code in the editor on the right to output a deep search path starting from a vertex, with four spaces between vertices.

Input and output instructions

Input instructions: The first line contains the number of vertices n and the number of edges e. The second line contains n vertex symbols. The next line e contains e edges. The two characters in each line represent an edge of the undirected graph. The last line contains only one character, which represents deep search. Start vertex output description: A path with four spaces between vertices.

Test instruction

The platform will test the code you write:

Test input:

4 5

a b c d

a b

a c

a d

b c

c d

c

Test output:

c a b d

Reference Code

//算法6.5 采用邻接矩阵表示图的深度优先搜索遍历
#include <iostream>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstring>

#define IOS std::ios::sync_with_stdio(false)
//#define YES cout << "1"
//#define NO cout << "0"
#define MaxInt 0x3f
#define MVNum 100
#define OK 1
#define ERROR 0

const int N = 1003;

using namespace std;
typedef long long LL;
typedef char VerTexType;					//假设顶点的数据类型为字符型 
typedef int ArcType;                 		//假设边的权值类型为整型 

//------------图的邻接矩阵------------------
typedef struct
{ 
	VerTexType vexs[MVNum];            		//顶点表 
	ArcType arcs[MVNum][MVNum];      		//邻接矩阵 
	int vexnum, arcnum;                		//图的当前点数和边数 
}Graph;

bool visited[MVNum];           				//访问标志数组,其初值为"false" 
int FirstAdjVex(Graph G , int v);			//返回v的第一个邻接点
int NextAdjVex(Graph G , int v , int w);	//返回v相对于w的下一个邻接点

int LocateVex(Graph G , VerTexType v){
	//确定点v在G中的位置
	for(int i = 0; i < G.vexnum; ++i)
		if(G.vexs[i] == v)
			return i;
	return -1;
}//LocateVex

void CreateUDN(Graph &G){ 
    //采用邻接矩阵表示法,创建无向网G 
	int i , j , k;
    cin >> G.vexnum >> G.arcnum;							//输入总顶点数,总边数

    for(i = 0; i < G.vexnum; ++i){   
		cin >> G.vexs[i];                        			//依次输入点的信息 
	}	
	

    for(i = 0; i < G.vexnum; ++i)                			//初始化邻接矩阵,边的权值均置为极大值MaxInt 
		for(j = 0; j < G.vexnum; ++j)   
			G.arcs[i][j] = 0;  

	for(k = 0; k < G.arcnum;++k){							//构造邻接矩阵 
		VerTexType v1 , v2;
		cin >> v1 >> v2;									//输入一条边依附的顶点及权值
		i = LocateVex(G, v1);  j = LocateVex(G, v2);		//确定v1和v2在G中的位置,即顶点数组的下标 
		G.arcs[j][i] = G.arcs[i][j] = 1;					//置<v1, v2>的对称边<v2, v1>的权值为w 
	}//for
}//CreateUDN 

void DFS(Graph G, int v)
{        		
	cout << G.vexs[v] <<"    ";
	visited[v] = true;
	for(int w = FirstAdjVex(G, v); w >= 0; w = NextAdjVex(G, v, w))
	if(!visited[w]) DFS(G, w);
}//DFS

int FirstAdjVex(Graph G, int v)
{
	for(int i = 0; i < G.vexnum; ++ i)
    	if(G.arcs[v][i] == 1 && visited[i] == false)
			return i;
	return -1;
}//FirstAdjVex

int NextAdjVex(Graph G, int v, int w)
{
	int i;
	for(i = w ; i < G.vexnum ; ++ i)
		if(G.arcs[v][i] == 1 && visited[i] == false)
			return i;
	return -1;
}//NextAdjVex

int main(){
	
	Graph G;

	CreateUDN(G);
	VerTexType c;
	cin >> c;

	int i;
	for(i = 0 ; i < G.vexnum ; ++i){
		if(c == G.vexs[i])
			break;
	}
	DFS(G , i);

	return 0;
}//main

Level 2: Algorithm 6.6 uses adjacency lists to represent deep searches of graphs

mission details

The task of this level: write a deep search program that uses adjacency lists to represent graphs.

related information

In order to complete this task, you need to master: 1. How to create an adjacency list 2. How to perform a deep search on a graph.

Programming requirements

According to the prompts, add code in the editor on the right to output a deep search path starting from a vertex, with four spaces between vertices.

Input and output instructions

Input instructions: The first line contains the number of vertices n and the number of edges e. The second line contains n vertex symbols. The next line e contains e edges. The two characters in each line represent an edge of the undirected graph. The last line contains only one character, which represents deep search. Start vertex output description: A path with four spaces between vertices.

Test instruction

The platform will test the code you write:

Test input:

4 5

a b c d

a b

a c

a d

b c

c d

c

Test output:

c a b d

Reference Code

//算法6.6 采用邻接表表示图的深度优先搜索遍历
#include <iostream>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstring>

#define IOS std::ios::sync_with_stdio(false)
//#define YES cout << "1"
//#define NO cout << "0"
#define MaxInt 0x3f
#define MVNum 100
#define OK 1
#define ERROR 0

const int N = 1003;

using namespace std;
typedef long long LL;
typedef char VerTexType;					//假设顶点的数据类型为字符型 
typedef int ArcType;                 		//假设边的权值类型为整型 

//-------------图的邻接表---------------------
typedef struct ArcNode						//边结点
{                		 
    int adjvex;                          	//该边所指向的顶点的位置 
    struct ArcNode *nextarc;          		//指向下一条边的指针 
}ArcNode; 

typedef struct VNode
{ 
    VerTexType data;                    	//顶点信息
    ArcNode *firstarc;                		//指向第一条依附该顶点的边的指针 
}VNode, AdjList[MVNum];               		//AdjList表示邻接表类型 

typedef struct
{
    AdjList vertices;                 		//邻接表 
    int vexnum, arcnum;              		//图的当前顶点数和边数 
}ALGraph;

bool visited[MVNum];           				//访问标志数组,其初值为"false" 

int LocateVex(ALGraph G , VerTexType v)
{
	for(int i = 0; i < G.vexnum; ++i)
		if(G.vertices[i].data == v)
			return i;
	return -1;
}//LocateVex

void CreateUDG(ALGraph &G){ 
	//采用邻接表表示法,创建无向图G
	int i , k;
	cin >> G.vexnum >> G.arcnum;				//输入总顶点数,总边数 
	for(i = 0; i < G.vexnum; ++i){          	//输入各点,构造表头结点表
		cin >> G.vertices[i].data;           	//输入顶点值 
		G.vertices[i].firstarc=NULL;			//初始化表头结点的指针域为NULL 
    }//for
	for(k = 0; k < G.arcnum;++k){        		//输入各边,构造邻接表
		VerTexType v1 , v2;
		int i , j;
		cin >> v1 >> v2;                 		//输入一条边依附的两个顶点
		i = LocateVex(G, v1);  j = LocateVex(G, v2);
		//确定v1和v2在G中位置,即顶点在G.vertices中的序号 
		
		ArcNode *p1=new ArcNode;               	//生成一个新的边结点*p1 
		p1->adjvex=j;                   		//邻接点序号为j 
		p1->nextarc= G.vertices[i].firstarc;  G.vertices[i].firstarc=p1;  
		//将新结点*p1插入顶点vi的边表头部
		
		ArcNode *p2=new ArcNode;                //生成另一个对称的新的边结点*p2 
		p2->adjvex=i;                   		//邻接点序号为i 
		p2->nextarc= G.vertices[j].firstarc;  G.vertices[j].firstarc=p2;  
		//将新结点*p2插入顶点vj的边表头部 
    }//for 
}//CreateUDG

void DFS(ALGraph G, int v)	//图G为邻接表类型 
{        			
	ArcNode *p;
	cout << G.vertices[v].data << "    ";
	
	visited[v] = true;
	p = G.vertices[v].firstarc;
	
	while(p)
	{
		if(!visited[p -> adjvex])  DFS(G, p -> adjvex);
		p = p -> nextarc;
	}
}//DFS

int main(){
	ALGraph G;
	CreateUDG(G);
	VerTexType c;
	cin >> c;
	
	int i;
	for(i = 0 ; i < G.vexnum ; ++i){
		if(c == G.vertices[i].data)
			break;
	}
	
	DFS(G , i);
	return 0;
}//main

Level 3: Algorithm 6.4 Deep search of non-connected graph - adjacency matrix representation graph

mission details

The task of this level: write a deep search program that uses adjacency lists to represent graphs.

related information

In order to complete this task, you need to master: 1. How to create an adjacency list 2. How to perform a deep search on a graph.

Programming requirements

According to the prompts, add code in the editor on the right to output a deep search path starting from a vertex, with four spaces between vertices.

Input and output instructions

Input instructions: The first line contains the number of vertices n and the number of edges e. The second line contains n vertex symbols. The next line e contains e edges. The two characters in each line represent an edge of the undirected graph. The last line contains only one character, which represents deep search. Start vertex output description: A path with four spaces between vertices.

Test instruction

The platform will test the code you write:

Test input:

6 6

a b c d e f

a b

a c

a d

c d

b d

e f

Test output:

a b d c

e f

Reference Code

//算法6.4 深度优先搜索遍历非连通图
#include <iostream>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstring>

#define IOS std::ios::sync_with_stdio(false)
//#define YES cout << "1"
//#define NO cout << "0"
#define MaxInt 0x3f
#define MVNum 100
#define OK 1
#define ERROR 0

const int N = 1003;

using namespace std;
typedef long long LL;
typedef char VerTexType;					//假设顶点的数据类型为字符型 
typedef int ArcType;                 		//假设边的权值类型为整型 
	
//-------------图的邻接矩阵-----------------
typedef struct
{ 
	VerTexType vexs[MVNum];            			//顶点表 
	ArcType arcs[MVNum][MVNum];      			//邻接矩阵 
	int vexnum, arcnum;                			//图的当前点数和边数 
}Graph;

bool visited[MVNum];           					//访问标志数组,其初值为"false" 
int FirstAdjVex(Graph G , int v);				//返回v的第一个邻接点
int NextAdjVex(Graph G , int v , int w);		//返回v相对于w的下一个邻接点

int LocateVex(Graph G , VerTexType v){
	//确定点v在G中的位置
	for(int i = 0; i < G.vexnum; ++i)
		if(G.vexs[i] == v)
			return i;
		return -1;
}//LocateVex

void CreateUDN(Graph &G){ 
    //采用邻接矩阵表示法,创建无向网G 
	int i , j , k;
    cin >> G.vexnum >> G.arcnum;								//输入总顶点数,总边数
	for(i = 0; i < G.vexnum; ++i)   
		cin >> G.vexs[i];                        				//依次输入点的信息 

    for(i = 0; i < G.vexnum; ++i)                				//初始化邻接矩阵,边的权值均置为极大值MaxInt 
		for(j = 0; j < G.vexnum; ++j)   
			G.arcs[i][j] = 0;  

	for(k = 0; k < G.arcnum;++k){								//构造邻接矩阵 
		VerTexType v1 , v2;
		cin >> v1 >> v2;										//输入一条边依附的顶点及权值
		i = LocateVex(G, v1);  j = LocateVex(G, v2);			//确定v1和v2在G中的位置,即顶点数组的下标 
		G.arcs[j][i] = G.arcs[i][j] = 1;						//置<v1, v2>的对称边<v2, v1>的权值为w 
	}//for
}//CreateUDN 

void DFS(Graph G, int v)
{        								
	cout << G.vexs[v];

	visited[v] = true;
	for(int w = FirstAdjVex(G, v); w >= 0; w = NextAdjVex(G, v, w))
	{
		if(!visited[w])  
		{
			cout<<"    ";
			DFS(G,w);
		}
	}
}//DFS

void DFSTraverse(Graph G){ 
	//对非连通图G做深度优先遍历 
	/**************************Begin*************************/
for(int v=0;v<G.vexnum;++v)  visited[v]=false;
for(int v=0;v<G.vexnum;++v)  
if(!visited[v])  
{cout<<endl;
    DFS(G,v);

}

    /**************************End****************************/
}//DFSTraverse 

int FirstAdjVex(Graph G , int v){
	//返回v的第一个邻接点
	int i;
	for(i = 0 ; i < G.vexnum ; ++i){
		if(G.arcs[v][i] == 1 && visited[i] == false)
			return i;
	}
	return -1;
}//FirstAdjVex

int NextAdjVex(Graph G , int v , int w){
	//返回v相对于w的下一个邻接点
	int i;
	for(i = w ; i < G.vexnum ; ++i){
		if(G.arcs[v][i] == 1 && visited[i] == false)
			return i;
	}
	return -1;
}//NextAdjVex

int main(){

	Graph G;

	CreateUDN(G);
	DFSTraverse(G);

	return 0;
}//main

The author has something to say

If you feel that what the blogger said is useful to you, please click "Follow" to support it. We will continue to update such issues...

 

 

 

Guess you like

Origin blog.csdn.net/weixin_62075168/article/details/128202150