第八天 有向路径检查

来源:互联网 发布:云购源码 编辑:程序博客网 时间:2024/06/05 08:56

题目中数据结构下一点的指针,让我想到了广度优先的思路。

大致想法:1. 从任一个点出发,找路径,有向共两次; 2. 用队列的思想,不断把新邻居压人; 3. 注意哪些点已经访问过了,避免环以及提高效率; 4. 注意边界情况。

/*struct UndirectedGraphNode {    int label;    vector<struct UndirectedGraphNode *> neighbors;    UndirectedGraphNode(int x) : label(x) {}};*/class Path {public:    bool checkPath(UndirectedGraphNode* a, UndirectedGraphNode* b) {        // write code here        if (!a) return false;        if (!b) return false;        if (a == b) return true;        // a->b        bool meet[1000];// 只是随意取了一个较大的值        memset(meet, false, sizeof(bool) * 1000);        queue<UndirectedGraphNode*> q;        q.push(a);        while (!q.empty())          {            UndirectedGraphNode* temp = q.front();            q.pop();            for (int i = 0; i < temp->neighbors.size(); i ++)            {                if (b == temp->neighbors[i])                    return true;                                    if (!meet[temp->neighbors[i]->label])                {                    q.push(temp->neighbors[i]);                    meet[temp->neighbors[i]->label] = true;                 }                            }        }        // b->a        memset(meet, false, sizeof(bool) * 1000);        q.push(b);        while (!q.empty())          {            UndirectedGraphNode* temp = q.front();            q.pop();            for (int i = 0; i < temp->neighbors.size(); i ++)            {                if (a == temp->neighbors[i])                    return true;                                    if (!meet[temp->neighbors[i]->label])                {                    q.push(temp->neighbors[i]);                    meet[temp->neighbors[i]->label] = true;                  }                            }        }                return false;    }};


0 0
原创粉丝点击