#include<bits/stdc++.h>
using namespace std;
//用二维数组存图 (邻接矩阵)
int mp[10][10]={0},book[101];
int n,sum=0;
void dfs(int cur){ //深搜遍历
int i;
cout<<cur<<" ";
sum++;
if(sum==n)
return ;
for(int i=1;i<=n;i++)
{
if(mp[cur][i]==1&&book[i]==0)
{
book[i]=1;
dfs(i);
}
}
return ;
}
int main()
{
int m;//m条边 ,n个顶点
int start,end;
cin>>n>>m;//每条边都有终点起点
while(m--)
{
scanf("%d %d",&start,&end);
mp[start][end]=1;//value;//有向
mp[end][start]=1;//为无向边
}
//图的遍历
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(mp[i][j])
cout<<mp[i][j]<<" ";
else
cout<<0<<" ";
}
cout<<endl;
}
book[1]=1;
dfs(1);
return 0;
}
图的邻接矩阵与深度遍历
最新推荐文章于 2023-12-05 09:10:12 发布