一:深度优先遍历(DFS)
每次沿着路径到不能再前进的时候才退回到最近的岔道口
每一次DFS过程可以遍历一个连通分量,遍历所有联通分量即遍历图
//邻接矩阵存储
const int maxv=10000;
const int INF=1000000000;
bool vis[maxv]={false};
int n,G[maxv][maxv];
void DFS(int u,int depth){
vis[u]=true;
for(int v=0;v<maxv;v++){
if(vis[i]==false&&G[u][v]!=INF){
DFS(v,depth+1);
}
}
}
void DFSTrave(){
for(int u=0;u<maxv;u++){
if(vis[u]==false){
DFS(u,1);
}
}
}
//邻接表存储
vector<int> Adj[maxv];
int n;
void DFS(int u,int depth){
vis[u]=true;
for(int i=0;i<Adj[u].size();i++){
int v=Adj[u][i];
if(vis[v]==false){
DFS(v,depth+1);
}
}
}
void DFSTrave(){
for(int u=0;u<maxv;u++){
if(vis[u]==false){
DFS(u,1);
}
}
}
二:广度优先遍历(BFS)
使用一个队列,通过反复取出队首顶点,将该顶点可到达的未曾加入过队列的顶点全部入队,直到队列为空时遍历结束
同DFS,遍历所有联通分量,即遍历完图
//邻接矩阵存储
int n,G[maxv][maxv];
bool inq[maxv]={false};//标记有没有进过队列
void BFS(int u){
queue<int> q;
q.push(u);
inq[u]=true;
while(!q.empty()){
int u=q.front();
q.pop();
for(int v=0;v<n;v++){
if(inq[v]==false&&G[u][v]!=INF){
q.push(v);
inq[v]=true;
}
}
}
}
//邻接表存储
vector(int) Adj[maxv];
int n;
bool inq[maxv]={false};
void BFS(int u){
queue<int> q;
q.push(u);
inq[u]=true;
while(!q.empty()){
int u=q.fornt();
q.pop();
for(int i=0;i<Adj[u].size();i++){
int v=Adj[u][i];
if(inq[v]!=false){
q.push(v);
inq[v]==ture;
}
}
}
}
void BFSTrave(){
for(int u=0;u<n;u++){
if(inq[u]==false){
BFS(u);
}
}
}
//如果需要配合层号的传递关系,则在结构体中定义层号,在队列循环中处理层数
struct Node{
int v;
int layer;
}
vector<Node> Adj[maxv];
void BFS(int s){
queue<Node> q;
Node start;
start.v=s;
start.layer=0;
q.push(start);
inq[start.v]=true;
while(!q.empty()){
Node topNode=q.front();
q.pop();
int u=topNode.v;
for(int i=0;i<Adj[u].size();i++){
Node next=Adj[u][i];
next.layer=topNode.layer+1;
if(inq[next.v]==false){
q.push(next);
inq[next.v]=true;
}
}
}
}