《程式員面試金典》有向路徑檢查,程式員面試金典

來源:互聯網
上載者:User

《程式員面試金典》有向路徑檢查,程式員面試金典

【 聲明:著作權,轉載請標明出處,請勿用於商業用途。  聯絡信箱:libin493073668@sina.com】


題目連結:http://www.nowcoder.com/practice/1b83885969f14329bf9222c1c54469a7?rp=1&ru=/ta/cracking-the-coding-interview&qru=/ta/cracking-the-coding-interview/question-ranking


題目描述
對於一個有向圖,請實現一個演算法,找出兩點之間是否存在一條路徑。
給定圖中的兩個結點的指標UndirectedGraphNode* a,UndirectedGraphNode* b(請不要在意資料類型,圖是有向圖),請返回一個bool,代表兩點之間是否存在一條路徑(a到b或b到a)。

思路
一道簡單的圖的遍曆問題,對於已經訪問過的結點我們要做標記,防止死迴圈


/*struct UndirectedGraphNode {    int label;    vector<struct UndirectedGraphNode *> neighbors;    UndirectedGraphNode(int x) : label(x) {}};*/class Path{public:bool checkPath(UndirectedGraphNode* a, UndirectedGraphNode* b){// write code hereif(a==nullptr)return false;if(b==nullptr)return false;if(a == b)return true;return hasPath(a,b) || hasPath(b,a);}bool hasPath(UndirectedGraphNode *a,UndirectedGraphNode *b){queue<UndirectedGraphNode*> Q;map<int,bool> vis;Q.push(a);vis[a->label] = true;while(!Q.empty()){UndirectedGraphNode *cur = Q.front();Q.pop();if(cur==b)return true;for(UndirectedGraphNode *node:cur->neighbors){if(vis[node->label]==true)continue;vis[node->label] = true;if(node==b)return true;Q.push(node);}}return false;}};


著作權聲明:本文為博主原創文章,如果轉載,請註明出處

聯繫我們

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