T1.图的深度优先遍历:
手写栈版:
#include<bits/stdc++.h>
using namespace std;
int n;
int st[105];
int top;// 栈顶
bool vis[105];// 0 表示没有被遍历,反之则为 被遍历了
int g[105][105];//g[i][j]=0 表示不连接
int main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>g[i][j];
}
}
// 模拟用栈深度优先遍历
// 以下为手动将 1 入栈
st[++top]=1;// 先让顶点 1 进栈
vis[1]=1;// 把顶点n 1 标记为已遍历
cout<<1;
//以上为手动将 1 入栈
while(top){// 只要栈不空
bool flag=0;
int i=st[top];//先找到栈顶的点
for(int j=1;j<=n;j++){
if(g[i][j]==1&&vis[j]==0){// 找到了
flag=1;// 标记找到,继续
st[++top]=j;
vis[j]=1;
cout<<'-'<<j;
break;// 退出
}
}
if(flag==0){
--top;// 出栈
}
}
return 0;
}递归版:
#include<bits/stdc++.h>
using namespace std;
int n;
int g[105][105];
bool vis[105];
void dfs(int i){
vis[i]=1;
for(int j=1;j<=n;j++){
if(g[i][j]==1&&vis[j]==0){
cout<<'-'<<j;
dfs(j);
}
}
}
signed main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>g[i][j];
}
}
cout<<1;
dfs(1);
return 0;
}宽度优先遍历:
#include<bits/stdc++.h>
using namespace std;
int n;
int g[105][105];
int q[105],head,tail;
bool vis[105];
signed main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>g[i][j];
}
}
q[++tail]=1;
cout<<1;
vis[1]=1;
while(head<tail){
int i=q[++head];
for(int j=1;i<=j;i++){
if(g[i][j]==1&&vis[j]==0){
cout<<'-'<<j;
vis[j]=1;
q[++tail]=1;
}
}
}
return 0;
}