演算法導論-----圖(深度優先搜尋)__演算法

來源:互聯網
上載者:User

嘗試優先策略:只要可能,就在圖中盡量深入,深度優先搜尋總是對最近才發現的結點v的出發邊進行探索,直到該結點的所有出發邊都被發現為止。一旦結點v的所有出發邊都被發現,搜尋則回溯到v的前驅結點,來搜尋該前驅結點的出發邊。該過程一直持續到從源結點可以達到的所有結點都被發現為止。如果還存在尚未發現的結點,則深度優先搜尋將從這些未被發現的結點中任選一個作為新的源結點,重複此過程。

#include <iostream>using namespace std;int   time;typedef enum  Color{GRAY,WHITE,BLACK}COLOR;typedef  struct Node{int    count;         //邊的條數int    d;             //被發現時間int    f;             //搜尋完成時間int    vertex;        //頂點struct Node* p;        //父結點COLOR  color;}NODE,*NODE_POINT;typedef  struct Graph{int    value;//邊的權值struct Node* link;}GRAPH,*GRAPH_POINT;void DFS_VISIT(GRAPH** graph,NODE_POINT node){int   j=0;time=time+1;node->d=time;node->color=GRAY;for(j=0;j<node->count;++j){if(graph[node->vertex-1][j].link->color==WHITE){graph[node->vertex-1][j].link->p=node;DFS_VISIT(graph,graph[node->vertex-1][j].link);}}node->color=BLACK;time=time+1;node->f=time;}int _tmain(int argc, _TCHAR* argv[]){NODE  node[5];int   i;GRAPH    **graph;graph=(GRAPH**)malloc(5*sizeof(GRAPH*));graph[0]=(GRAPH*)malloc(2*sizeof(GRAPH));graph[1]=(GRAPH*)malloc(4*sizeof(GRAPH));graph[2]=(GRAPH*)malloc(2*sizeof(GRAPH));graph[3]=(GRAPH*)malloc(3*sizeof(GRAPH));graph[4]=(GRAPH*)malloc(3*sizeof(GRAPH));for(i=0;i<5;++i){node[i].vertex=i+1;node[i].color=WHITE;node[i].p=NULL;}node[0].count=2;node[1].count=4;node[2].count=2;node[3].count=3;node[4].count=3;graph[0][0].link=&node[1];graph[0][1].link=&node[4];graph[1][0].link=&node[0];graph[1][1].link=&node[4];graph[1][2].link=&node[2];graph[1][3].link=&node[3];graph[2][0].link=&node[1];graph[2][1].link=&node[3];graph[3][0].link=&node[1];graph[3][1].link=&node[4];graph[3][2].link=&node[2];graph[4][0].link=&node[3];graph[4][1].link=&node[0];graph[4][2].link=&node[1];for(i=0;i<5;++i){if(node[i].color==WHITE){DFS_VISIT(graph,&node[i]);}}    for(i=0;i<5;++i){free(graph[i]);}free(graph);system("pause");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.