DFS
#include<cstdio>
#include<string>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
int INF = 100000;
int n;//顶点数
int G[1000][1000];//图的矩阵表达
int vis[1000] = {0};//标记已访问的数组
void DFS(int u,int depth){
vis[u] = 1;
for(int i = 0;i < n;i++){
if(vis[i] == 0 && G[i][u] != INF){
DFS(i,depth+1);
}
}
}
int main(){
for(int i = 0;i < n;i++){
if(vis[i] == 0){
DFS(i,1);
}
}
}
BFS
#include<cstdio>
#include<string>
#include<vector>
#include <queue>
#include<iostream>
#include<algorithm>
using namespace std;
int INF = 100000;
int n;//顶点数
int G[1000][1000];//图的矩阵表达
int vis[1000] = {0};//标记已访问的数组
void BFS(int u){
queue<int> q;
q.push(u);
vis[u] = 1;
while(!q.empty()){
int u = q.front();
q.pop();
for(int i = 0;i < n;i++){
if(vis[i] == 0 && G[i][u] != INF){
q.push(i);
vis[i] = 1;
}
}
}
}