题目描述
给定一个图的邻接矩阵,给出一张以整数编号为顶点的图,其中0表示不相连,1表示相连。按深度和广度优先进行遍历,输出全部结果。要求,遍历时优先较小的顶点。如,若顶点0与顶点2,顶点3,顶点4相连,则优先遍历顶点2.
输入
顶点个数
邻接矩阵
输出
DFS
深度遍历输出(从0开始的节点遍历路径)
WFS
广度遍历输出(从0开始的节点遍历路径)
代码如下:
具体注释有空再加,懂得都懂,有手就行。
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
void DFS(int a[100][100],int i,int n)
{
stack<int> dfs;
dfs.push(i);
int check[100]= {0};
while(!dfs.empty())
{
int temp=dfs.top();
dfs.pop();
if(check[temp]==0)
{
cout<<temp<<" ";
check[temp]=1;
}
for(int j=n-1; j>=0; j--)
{
if(a[temp][j]==1)
{
dfs.push(j);
a[temp][j]=2;
}
}
for(int j=0; j<n; j++)
a[j][temp]=0;
}
}
void WFS(int a[100][100],int i,int n)
{
queue<int>wfs;
wfs.push(i);
int check[100]= {0};
while(!wfs.empty())
{
int temp=wfs.front();
wfs.pop();
if(check[temp]==0)
{
cout<<temp<<" ";
check[temp]=1;
}
for(int j=0; j<n; j++)
{
if(a[temp][j]==1)
{
wfs.push(j);
a[temp][j]=2;
}
}
for(int j=0; j<n; j++)
a[j][temp]=0;
}
}
int main()
{
int n;
int pic[100][100]= {0};
cin>>n;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
cin>>pic[i][j];
cout<<"DFS"<<endl;
for(int i=0; i<n; i++)
{
int paste [100][100];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
paste[i][j]=pic[i][j];
DFS(paste,i,n);
cout<<endl;
}
cout<<"WFS"<<endl;
for(int i=0; i<n; i++)
{
int paste [100][100];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
paste[i][j]=pic[i][j];
WFS(paste,i,n);
cout<<endl;
}
}