交个崔鹏题 OJ实践1-C /图的广度搜索/C++

#include<iostream> 
#include<malloc.h>
#include<queue>
using namespace std;
#define MAX 10
typedef int E;
typedef struct Node{
	int nextVex;
	struct Node *next;
}*node;

struct HeadNode{
	E element;
	struct Node *next;
};
typedef struct GraphTable{
	int vex,edge;
	struct HeadNode vertex[MAX];
} *Graph;
Graph Create(){
	Graph g = (Graph)malloc(sizeof(struct GraphTable));
	g->edge=g->vex=0;
	return g;
}
void addVex(Graph g,E e){
	g->vertex[g->vex].element=e;
	g->vertex[g->vex].next=NULL;
	g->vex++;
}
int getIndexByElem(Graph g,E v){
	int i=0;
	while(true){
		if(g->vertex[i].element==v)
			return i;
		i++;
	}
}
void addEdge(Graph g, E v1, E v2){
	int a=getIndexByElem(g,v1);
	int b=getIndexByElem(g,v2);

	node nd=g->vertex[a].next;
	node newNode=(node)malloc(sizeof(struct Node));
	newNode->next=NULL;
	newNode->nextVex=b;
	if(!nd)
		g->vertex[a].next=newNode;
	else
	{
		while(nd->next)
		{
			if(nd->nextVex==b) return;
			if(nd->next) nd=nd->next;
		}
		nd->next=newNode;
	}
	g->edge++;
}
void printTable(Graph g){
	for(int i=0;i<g->vex;i++){
		cout<<i<<"|"<<g->vertex[i].element;
		node nd=g->vertex[i].next;
		while(nd){
			cout<<"->"<<nd->nextVex;
			nd=nd->next;
		}
		cout<<endl;
	}
	
}
queue<int> Q;

int DFS(Graph g,int startVex,int targetVex,int *visited){
	
	Q.push(g->vertex[startVex].element);
	if(startVex==targetVex) return 1;
	visited[startVex]=1;
	node nd=g->vertex[startVex].next;
	while(nd){
		if(!visited[nd->nextVex])
			if(DFS(g,nd->nextVex,targetVex,visited))
				return 1;
		nd=nd->next;
	}
	return 0;
}
void printQueue(int n){
	for (int i =0;i<n;i++){
		cout<<Q.front();
		if(i<n-1)cout<<" ";
		Q.pop();
	}
	cout<<endl;
}
int main(){
	Graph graph = Create();
	int n;
	cin>>n;
	for(int c=1;c<=n;++c)
		addVex(graph,c);
	int a,b;
	while(cin>>a>>b)
		addEdge(graph,a,b);
	int arr[graph->vex];
	for(int i=0;i<=graph->vex;i++)arr[i]=0;
	DFS(graph,0,n,arr);
	printQueue(n);
	return 0;
}
posted @ 2023-12-21 18:51  Happy_Eric  阅读(5)  评论(0编辑  收藏  举报