圖的遍曆,非遞迴版本,深度優先遍曆

來源:互聯網
上載者:User

 

UndirectedGraphNode 為圖節點, label 儲存節點資料, visited 表示節點是否已被訪問過, neighbors 表示相串連的節點。

利用 stack 實現對圖的深度遍曆,stack 由 list 的 back(), push_back(), pop_back 方法實現。

遍曆思路: 將第一個節點壓入 stack_node 中, stack_node.back() 表示當前訪問的節點。

若存在尚未訪問的鄰接節點,則將其壓入 stack_node 中,標記為已訪問,並將新壓入的這個節點作為當前節點,繼續探索。

若不存在尚未訪問的鄰接節點,則彈出當前節點,將 stack_node 的下一個節點作為當前節點,繼續探索。


執行上面兩個檢測,直到 stack_node 全部彈出,則表示全部節點已被訪問過。遍曆完成。


struct UndirectedGraphNode {int label;bool visited = false;    vector<UndirectedGraphNode *> neighbors;    UndirectedGraphNode(int x) : label(x) {};};/** * 非遞迴版本,遍曆圖的所有節點,深度優先遍曆 * */void visited_non_recusive(UndirectedGraphNode* node){list<UndirectedGraphNode*> stack_node;stack_node.push_back(node);print_node(node);node->visited = true;UndirectedGraphNode* tmp;UndirectedGraphNode* iter_tmp;while (stack_node.size() > 0) {tmp = stack_node.back();int i = 0;for ( ; i < tmp->neighbors.size(); i++) {iter_tmp = tmp->neighbors[i];if (iter_tmp->visited == false) {print_node(iter_tmp);iter_tmp->visited = true;stack_node.push_back(iter_tmp);break;}}if (i == tmp->neighbors.size()) {stack_node.pop_back();}}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.