深度优先遍历
Description
按照给定的起始顶点深度优先遍历给定的无向图,尝试所有可能的遍历方式,打印遍历过程中出现的最大深度。
Input
输入第一行是用例个数,后面每个用例使用多行表示,用例的第一行是图中节点的个数n和起始点,用空格隔开,后面n+1行为图的邻接矩阵,其中第一行为节点名称。值之间使用空格隔开。
Output
输出深度优先遍历中遇到的最大深度。
Sample Input 1
1 4 a a b c d a 0 1 1 0 b 1 0 1 0 c 1 1 0 1 d 0 0 1 0
Sample Output 1
4
#include <stdio.h>
#include <iostream>
#include<algorithm>
#define MAX_NUM 100
using namespace std;
int n;
int matrix[500+5][500+5];
int ans=-1,cnt;
int vis[500+5];
void dfs(int a){
if(a>=n) return;
for(int i=0;i<n;i++){
if(!vis[i]&&matrix[a][i]==1){//存在下一条边并且未被访问
vis[i]=1;
cnt++;
dfs(i);
}
}
ans = max(ans,cnt);
}
int main() {
int t;
cin>>t;
while(t-->0){
cin>>n;
char start;
int s;
cin>>start;
char node[n];
for(int i=0;i<n;i++) {
cin>>node[i];
if(node[i]==start)
s = i;
}
char rowTag;
for(int i=0;i<n;i++){
cin>>rowTag;
vis[i]=0;
for(int j=0;j<n;j++){
cin>>matrix[i][j];
matrix[j][i]=matrix[i][j];//无向图
}
}
cnt=0;
vis[s]=1;
dfs(s);
cout<<ans+1<<endl;//算上开始的点
}
return 0;
}