⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄

📁 数据结构里的dfs算法
💻
字号:
#include <iostream.h>

const int nmax=100;

typedef struct
{
	int data[nmax+1];    
    int adjmat[nmax+1][nmax+1];   
    int n,e;             
}mat_graph;

typedef struct node * pointer;

struct node 
{                 
	int no;                     
	pointer next;                  
};

typedef struct 
{
	int data;                    
	pointer first;
}headtype;                        

typedef struct
{
	headtype adjlist[nmax+1];            
	int n,e;                       
}lk_graph;                    

void dfsL(lk_graph *gl,int v);
void main()
{
	int i,j;
	mat_graph ga;
    ga.n=4;
	ga.e=4;
	ga.adjmat[1][2]=1;
	ga.adjmat[2][3]=1;
	ga.adjmat[3][1]=1;
	ga.adjmat[1][4]=1;
	lk_graph gl;
	pointer p;
	gl.n=ga.n;
	gl.e=ga.e;
	for(i=1;i<=gl.n;i++) gl.adjlist[i].first=NULL;
	for(i=1;i<=ga.n;i++)
		for(j=ga.n;j>=i;j--)
		{
			if(ga.adjmat[i][j]==0) continue;
			p=new node;                       
			p->no=j;                          
			p->next=gl.adjlist[i].first;
			gl.adjlist[i].first=p;
		}
		dfsL(&gl,1);
}

void dfsL(lk_graph *gl,int v)
{
	int S[nmax];                       
	pointer p;
	int top=-1;
	int visited[100];
	cout<<v<<" "; visited[v]=1;             
	S[++top]=v;
	do{
		p=gl->adjlist[S[top]].first;
		while(p!=NULL&&visited[p->no])  p=p->next;   
		if(p==NULL) top--;                          
		else {
			cout<<p->no<<" "; 
			visited[p->no]=1;             
			S[++top]=p->no;
		}
	}while (top!=-1);
	cout<<"dfsL completed"<<endl;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -