Lintcode 618. Search Graph Nodes 解题报告

[Problem]

Given a undirected graph, a node and a target, return the nearest node to given node which value of it is target, return NULL if you can't find.

There is a mapping store the nodes' values in the given parameters.

 Notice

It's guaranteed there is only one available solution

[Idea]

BFS

The solution provided here is quite typical as it use a queue to travese the graph node level by level if the given node could be set as the root node. Initially the queue is constructed with the only element, the root node. By next level, it means the neighbor list the current node holds.

Considering the possibility of loops, a hash map is introduced here to avoid duplicate visiting. Once a node is visited, it will be pushed into the hashmap.

[Code]

/**
 * Definition for Undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    /**
     * @param graph a list of Undirected graph node
     * @param values a hash mapping, <UndirectedGraphNode, (int)value>
     * @param node an Undirected graph node
     * @param target an integer
     * @return the a node
     */
    UndirectedGraphNode* searchNode(vector<UndirectedGraphNode*>& graph,
                                    map<UndirectedGraphNode*, int>& values,
                                    UndirectedGraphNode* node,
                                    int target) {
        // Write your code here
        queue<UndirectedGraphNode*> q;
        set<UndirectedGraphNode*> hash;
        
        q.push(node);
        hash.insert(node);
        while(!q.empty()) {
            UndirectedGraphNode* head = q.front();
            q.pop();
            if(values[head] == target) {
                return head;
            }
            for(UndirectedGraphNode* n : head->neighbors) {
                if(hash.find(n) == hash.end()) {
                    hash.insert(n);
                    q.push(n);
                }
            }
        }
        return NULL;
    }
};

[Reference]

  1. Lintcode: Search Graph Nodes
  2. Jiuzhang Solution for Search Graph Nodes

转载于:https://www.cnblogs.com/casperwin/p/7451205.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值