#include<iostream>
#include<queue>
using namespace std;
typedef int VertexType;
#define MaxVertexNum 100
typedef int EdgeType;
typedef struct{
VertexType Vex[MaxVertexNum];
EdgeType Edge[MaxVertexNum][MaxVertexNum];
int vexnum,arcnum;
bool visited[MaxVertexNum][MaxVertexNum];
}MGraph;
bool Adjacent(MGraph G,VertexType x,VertexType y){ //判断边<x,y>或者<y,x>是否存在
if(G.Edge[x-1][y-1]==1)
return true;
else return false;
}
int Neighbors(MGraph G,VertexType x){ //输出G的临接结点
for(int i=0;i<G.vexnum;i++){
if(G.Edge[x-1][i]==1){
cout<<i+1<<" ";
}
}
return 0;
}
int InsertVertex(MGraph &G,int x){
return 0;
}
int FirstNeighbor(MGraph &G,int x){ //图G中的顶点x的第一个邻接点,若有则返回顶点号,没有返回-1
for(int i=0;i<G.vexnum;i++){
if(G.Edge[x][i]==1&&G.visited[x][i]==false){
G.visited[x][i]=true;
return i;
}
}
return -1;
}
int NextNeighbor(MGraph &G,int x,int y){
for(int i=0;i<G.vexnum;i++){
if(G.Edge[x][i]==1&&G.visited[x][i]==false&&i!=(y)){
G.visited[x][i]=true;
return i;
}
}
return -1;
}
bool visited[MaxVertexNum];
void DFS(MGraph G,int v){
cout<<v<<" ";
visited[v]=true;
int w;
for(w=FirstNeighbor(G,v);w>=0;w=NextNeighbor(G,v,w)){
if(!visited[w]){
DFS(G,w);
}
}
}
bool DFSTraverse(MGraph G){
for(int v=0;v<G.vexnum;v++){
visited[v]=false;
}
for(int v=0;v<G.vexnum;v++){
if(!visited[v]){
DFS(G,v);
}
}
}
void BFS(MGraph G,VertexType v){
int w;
cout<<v<<" ";
queue<VertexType> Q;
visited[v]=true;
Q.push(v);
while(Q.size()){
int x=Q.front();
Q.pop();
for(w=FirstNeighbor(G,x);w>=0;w=NextNeighbor(G,x,w)){
if(!visited[w]){
cout<<w<<" ";
visited[w]=true;
Q.push(w);
}
}
}
}
void BFSTraverse(MGraph G){
for(int i=0;i<G.vexnum;i++){
visited[i]=false;
}
for(int i=0;i<G.vexnum;i++){
if(!visited[i])
BFS(G,i);
}
}
int main(){
MGraph G;
int vexnum,arcnum;
cin>>vexnum;
for(int i=1;i<=vexnum;i++){
G.Vex[i]=i;
}
G.vexnum=vexnum;
for(int i=0;i<vexnum;i++){
for(int j=0;j<vexnum;j++){
int n;
cin>>n;
G.Edge[i][j]=n;
G.visited[i][j]=false;
if(n==1){
G.arcnum++;
}
}
}
// cout<<int(Adjacent(G,2,3));
// Neighbors(G,2);
// BFSTraverse(G);
BFS(G,2);
// DFS(G,3);
return 0;
}
//5
//0 1 0 1 0
//1 0 1 0 1
//0 1 0 1 1
//1 0 1 0 0
//0 1 1 0 0
图的深度搜索和广度搜索代码c
最新推荐文章于 2024-04-19 18:08:13 发布