DFS

Posted on 2023-08-15 17:19  jacyoier  阅读(47)  评论(0)    收藏  举报

 

DFS方法1,不适用递归:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int main(){
 4     ios::sync_with_stdio(false);
 5     int a[10][10],stk[10],h[10];
 6     int n,top=0,k=0;
 7     h[1]=1;
 8     stk[0]=1;
 9     while(top>=0){
10         k++;
11         if(k>n) k=stk[top--];
12         else if(!h[k]&&a[stk[top]][k]){
13             cout<<"-"<<k;
14             h[k]=1;
15             stk[++top]=k;
16             k=0;
17         } 
18     }
19     return 0;
20 }

DFS方法2,适用递归:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int a[5][5]={{0,1,1,0,0},{1,0,1,1,1},{1,1,0,0,0},{0,1,0,0,1},{0,1,0,1,0}};
 4 int vis[1001]={0};
 5 void dfs(int x){
 6     vis[x]=1;
 7     for(int i=0;i<=4;i++){
 8         if(a[x][i]==1&&vis[i]==0){
 9             cout<<"V"<<i<<"->";
10             dfs(i);
11         }
12     }
13     return ;
14 }
15 int main(){
16     ios::sync_with_stdio(false);
17     vis[0]=1;
18     cout<<"V0->";
19     dfs(0);
20     return 0;
21 }

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3