原题复刻
思想的火花
1.dfs(邻接矩阵实现)
void dfs(graph &g,int v)
{
cout<<v<<" ";
vis[v]=1;
for(int w=firstadjves(g,v); w>=0; w=nextadjves(g,v,w))if(!vis[w])dfs(g,w);
}
2.其他函数介绍请移步HNUST-OJ -1963-邻接矩阵表示法:
代码实现
#include<bits/stdc++.h>
using namespace std;
#define MAX 100
typedef int VerTexType;
typedef int Arctype;
typedef struct
{
VerTexType vexs[MAX];
Arctype arcs[MAX][MAX];
int vexnum,arcnum;
}graph;
bool vis[MAX];
VerTexType vertexdata(const graph &g,int i)
{
return g.vexs[i];
}
int firstadjves(const graph &g,int v)
{
for(int j=0; j<g.vexnum; j++)if(g.arcs[v][j]==1)return j;
return -1;
}
int nextadjves(const graph &g,int v,int w)
{
for(int i=w+1; i<g.vexnum; i++)if(g.arcs[v][i]==1)return i;
return -1;
}
void createudg(graph &g)
{
cin>>g.vexnum;
for(int i=0; i<g.vexnum; i++)
{
for(int j=0; j<g.vexnum; j++)cin>>g.arcs[i][j];
}
}
void dfs(graph &g,int v)
{
cout<<v<<" ";
vis[v]=1;
for(int w=firstadjves(g,v); w>=0; w=nextadjves(g,v,w))if(!vis[w])dfs(g,w);
}
int main()
{
graph g;
createudg(g);
dfs(g,0);
}