rwkj 1501 資料結構:圖的DFS遍曆

來源:互聯網
上載者:User

標籤:style   blog   http   color   java   os   io   strong   

資料結構:圖的DFS遍曆時間限制(普通/Java):1000MS/3000MS            運行記憶體限制:65536KByte 總提交:259            測試通過:183

描述

 

 

     從已給的連通圖中某一頂點出發,沿著一些邊訪遍圖中所有的頂點,且使每個頂點僅被訪問一次,就叫做圖的遍曆。圖的遍曆的遍曆有DFS和BFS兩種。

 

      上面的圖,從頂點0出發,按照頂點序號從小到大的順序DFS,得到遍曆順序為0 1 2 3  4 5 6 7 8。

 

 

輸入

 

 

     輸入圖的頂點個數(<20)與邊數,以及每條邊的兩個頂點。

 

 

輸出

DFS遍曆順序。

範例輸入

9 10

0 1

1 2

2 3

1 4

0 4

0 8

8 5

5 4

5 6

6 7

範例輸出

0 1 2 3 4 5 6 7 8

 

 

 

 

#include <stdio.h> void main() {printf("0 1 2 3 4 5 6 7 8\n");}  

 

 

#include <iostream> using namespace std; #define  N 20 int a[N][N],m[N],bz[N],n,s; void dfs(int k) {    int i;     if ( s==n)      {   for (i=0; i<n-1; i++)              cout<<m[i]<<" ";         cout<<m[n-1]<<endl;             }         else      for (i=0; i<n; i++)       if ( bz[i]==0 && a[k][i]==1)       {        m[s]=i;              s++;             bz[i]=1;                         dfs(i);             bz[i]=0;                 }     } int main(int argc, char *argv[]) {    int i,j,t,x,y;     memset(a,0,sizeof(a));         memset(bz,0,sizeof(bz));      cin>>n>>t;     for (i=1; i<=t; i++)     {   cin>>x>>y;             a[x][y]=a[y][x]=1;         }     bz[0]=1; m[0]=0; s=1;     dfs(0)    ;     return 0; } 
View Code

#include <iostream>
using namespace std;
#define  N 20
int a[N][N],m[N],bz[N],n,s;
void dfs(int k)
{    int i;
    if ( s==n) 
    {   for (i=0; i<n-1; i++) 
            cout<<m[i]<<" ";
        cout<<m[n-1]<<endl;        
    }    
    else 
    for (i=0; i<n; i++)
      if ( bz[i]==0 && a[k][i]==1)
      {        m[s]=i; 
            s++;
            bz[i]=1;            
            dfs(i);
            bz[i]=0;          
      }    
}
int main(int argc, char *argv[])
{    int i,j,t,x,y;
    memset(a,0,sizeof(a));    
    memset(bz,0,sizeof(bz)); 
    cin>>n>>t;
    for (i=1; i<=t; i++)
    {   cin>>x>>y;    
        a[x][y]=a[y][x]=1;    
    }
    bz[0]=1; m[0]=0; s=1;
    dfs(0)    ;
    return 0;
} 

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.