技术控

    今日:91| 主题:49531
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Find all reachable nodes from every node present in a given set

[复制链接]
一贱终情 发表于 2016-10-8 21:37:01
312 10

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Given an undirected graph and a set of vertices, find all reachable nodes from every vertex present in the given set.
     Consider below undirected graph with 2 disconnected components.
   
Find all reachable nodes from every node present in a given set-1 (reachable,no,reachable,servers,chrome,not,reachable,still,reachable,reachableviawwan)
    [code]arr[] = {1 , 2 , 5}
Reachable nodes from 1 are  1, 2, 3, 4
Reachable nodes from 2 are 1, 2, 3, 4
Reachable nodes from 5 are 5, 6, 7[/code]         Method 1 (Simple)       One straight forward solution is to do aBFS traversal for every node present in the set and then find all the reachable nodes.
    Assume that we need to find reachable nodes for n nodes, the time complexity for this solution would be O(n*(V+E)) where V is number of nodes in the graph and E is number of edges in the graph. Please note that we need to call BFS as a separate call for every node without using the visited array of previous traversals because a same vertex may need to be printed multiple times. This seems to be an effective solution but consider the case when E = Θ(V 2 ) and n = V, time complexity becomes O(V 3 ).
           Method 2 (Efficient)    Since the given graph is undirected, all vertices that belong to same component have same set of reachable nodes. So we keep track of vertex and component mappings. Every component in the graph is assigned a number and every vertex in this component is assigned this number. We use the visit array for this purpose, the array which is used to keep track of visited vertices in BFS.
  [code]For a node u,
if visit is 0 then
    u has not been visited before
else // if not zero then
   visit represents the component number.

For any two nodes u and v belonging to same
component, visit is equal to visit[v][/code]   To store the reachable nodes, use a map m with key as component number and value as a vector which stores all the reachable nodes.
   To find reachable nodes for a node u return m[visit]
  Look at the pseudo code below in order to understand how to assign component numbers.
  [code]componentNum = 0
for i=1 to n       
    If visit is NOT 0 then
        componentNum++
         
        // bfs() returns a list (or vector)
        // for given vertex 'i'
        list = bfs(i, componentNum)
        m[visit]] = list[/code]  For the graph shown in the example the visit array would be.

Find all reachable nodes from every node present in a given set-2 (reachable,no,reachable,servers,chrome,not,reachable,still,reachable,reachableviawwan)

  For the nodes 1, 2, 3 and 4 the component number is 1. For nodes 5, 6 and 7 the component number is 2.
  C++ Implementation of above idea
  [code]// C++ program to find all the reachable nodes
// for every node present in arr[0..n-1].
#include
using namespace std;

// This class represents a directed graph using
// adjacency list representation
class Graph
{
public:
    int V;    // No. of vertices

    // Pointer to an array containing adjacency lists
    list *adj;

    Graph(int );  // Constructor

    void addEdge(int, int);

    vector BFS(int, int, int []);
};

Graph::Graph(int V)
{
    this->V = V;
    adj = new list[V+1];
}

void Graph::addEdge(int u, int v)
{
    adj.push_back(v); // Add w to v’s list.
    adj[v].push_back(u); // Add v to w’s list.
}

vector Graph::BFS(int componentNum, int src,
                                    int visited[])
{
    // Mark all the vertices as not visited
    // Create a queue for BFS
    queue queue;

    queue.push(src);

    // Assign Component Number
    visited[src] = componentNum;

    // Vector to store all the reachable nodes from 'src'
    vector reachableNodes;

    while(!queue.empty())
    {
        // Dequeue a vertex from queue
        int u = queue.front();
        queue.pop();

        reachableNodes.push_back(u);

        // Get all adjacent vertices of the dequeued
        // vertex u. If a adjacent has not been visited,
        // then mark it visited nd enqueue it
        for (auto itr = adj.begin();
                itr != adj.end(); itr++)
        {
            if (!visited[*itr])
            {
                // Assign Component Number to all the
                // reachable nodes
                visited[*itr] = componentNum;
                queue.push(*itr);
            }
        }
    }
    return reachableNodes;
}

// Display all the Reachable Nodes from a node 'n'
void displayReachableNodes(int n,
            unordered_map > m)
{
    vector temp = m[n];
    for (int i=0; i         cout << temp << " ";

    cout << endl;
}

// Find all the reachable nodes for every element
// in the arr
void findReachableNodes(Graph g, int arr[], int n)
{
    // Get the number of nodes in the graph
    int V = g.V;

    // Take a integer visited array and initialize
    // all the elements with 0
    int visited[V+1];
    memset(visited, 0, sizeof(visited));

    // Map to store list of reachable Nodes for a
    // given node.
    unordered_map > m;

    // Initialize component Number with 0
    int componentNum = 0;

    // For each node in arr[] find reachable
    // Nodes
    for (int i = 0 ; i < n ; i++)
    {
        int u = arr;

        // Visit all the nodes of the component
        if (!visited)
        {
            componentNum++;

            // Store the reachable Nodes corresponding to
            // the node 'i'
            m[visited] = g.BFS(componentNum, u, visited);
        }

        // At this point, we have all reachable nodes
        // from u, print them by doing a look up in map m.
        cout << "Reachable Nodes from " << u <<" are\n";
        displayReachableNodes(visited, m);
    }
}

// Driver program to test above functions
int main()
{
    // Create a graph given in the above diagram
    int V = 7;
    Graph g(V);
    g.addEdge(1, 2);
    g.addEdge(2, 3);
    g.addEdge(3, 4);
    g.addEdge(3, 1);
    g.addEdge(5, 6);
    g.addEdge(5, 7);

    // For every ith element in the arr
    // find all reachable nodes from query
    int arr[] = {2, 4, 5};

    // Find number of elements in Set
    int n = sizeof(arr)/sizeof(int);

    findReachableNodes(g, arr, n);

    return 0;
}[/code]  Output:
  [code]Reachable Nodes from 2 are
1 2 3 4
Reachable Nodes from 4 are
1 2 3 4
Reachable Nodes from 5 are
5 6 7[/code]   Time Complexity Analysis:
  n = Size of the given set
  E = Number of Edges
  V = Number of Nodes
  O(V+E) for BFS
  In worst case all the V nodes are displayed for each node present in the given, i.e only one component in the graph so it takes O(n*V) time.
  Worst Case Time Complexity : O(V+E) + O(n*V)
   This article is contributed by Chirag Agarwal . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.
  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
友荐云推荐




上一篇:Kuliza Interview Experience | Set 4 (On-Campus)
下一篇:10 Tips in Picking a Technology Stack for Web Developers
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

jeanb 发表于 2016-10-10 11:34:46
一贱终情 顶起!
回复 支持 反对

使用道具 举报

稀釋回憶 发表于 2016-10-10 13:30:04
胆子不小啊,居然让我抢到了沙发!
回复 支持 反对

使用道具 举报

haihai88 发表于 2016-10-26 13:35:11
要戒烟,早睡,好好的死。
回复 支持 反对

使用道具 举报

崭新的实质性 发表于 2016-10-26 16:52:31
我也顶起出售广告位
回复 支持 反对

使用道具 举报

佃成芊 发表于 2016-10-29 07:52:43
怀揣两块,胸怀500万!  
回复 支持 反对

使用道具 举报

邓符 发表于 2016-11-12 16:48:42
蜘蛛会不会上吊?
回复 支持 反对

使用道具 举报

zry 发表于 2016-11-18 07:56:13
我是应该赞一贱终情呢还是应该赞呢
回复 支持 反对

使用道具 举报

vip514 发表于 2016-11-18 13:52:16
房价越来越高,所以,好男人越来越少……
回复 支持 反对

使用道具 举报

gqbrr590 发表于 2016-11-18 14:14:05
有些的时候,正是为了爱才悄悄躲开.躲开的是身影,躲不开的却是那份默默的情怀。
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表