技术控

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

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

[复制链接]
一贱终情 发表于 2016-10-8 21:37:01
511 10
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

Find all reachable nodes from every node present in a given set
   
  1. arr[] = {1 , 2 , 5}
  2. Reachable nodes from 1 are  1, 2, 3, 4
  3. Reachable nodes from 2 are 1, 2, 3, 4
  4. Reachable nodes from 5 are 5, 6, 7
复制代码
        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.
  1. For a node u,
  2. if visit[u] is 0 then
  3.     u has not been visited before
  4. else // if not zero then
  5.    visit[u] represents the component number.

  6. For any two nodes u and v belonging to same
  7. component, visit[u] is equal to visit[v]
复制代码
  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.
  1. componentNum = 0
  2. for i=1 to n       
  3.     If visit[i] is NOT 0 then
  4.         componentNum++
  5.          
  6.         // bfs() returns a list (or vector)
  7.         // for given vertex 'i'
  8.         list = bfs(i, componentNum)
  9.         m[visit[i]]] = list
复制代码
For the graph shown in the example the visit array would be.
   

Find all reachable nodes from every node present in a given set

Find all reachable nodes from every node present in a given set

  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
  1. // C++ program to find all the reachable nodes
  2. // for every node present in arr[0..n-1].
  3. #include <bits/stdc++.h>
  4. using namespace std;

  5. // This class represents a directed graph using
  6. // adjacency list representation
  7. class Graph
  8. {
  9. public:
  10.     int V;    // No. of vertices

  11.     // Pointer to an array containing adjacency lists
  12.     list<int> *adj;

  13.     Graph(int );  // Constructor

  14.     void addEdge(int, int);

  15.     vector<int> BFS(int, int, int []);
  16. };

  17. Graph::Graph(int V)
  18. {
  19.     this->V = V;
  20.     adj = new list<int>[V+1];
  21. }

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

  27. vector<int> Graph::BFS(int componentNum, int src,
  28.                                     int visited[])
  29. {
  30.     // Mark all the vertices as not visited
  31.     // Create a queue for BFS
  32.     queue<int> queue;

  33.     queue.push(src);

  34.     // Assign Component Number
  35.     visited[src] = componentNum;

  36.     // Vector to store all the reachable nodes from 'src'
  37.     vector<int> reachableNodes;

  38.     while(!queue.empty())
  39.     {
  40.         // Dequeue a vertex from queue
  41.         int u = queue.front();
  42.         queue.pop();

  43.         reachableNodes.push_back(u);

  44.         // Get all adjacent vertices of the dequeued
  45.         // vertex u. If a adjacent has not been visited,
  46.         // then mark it visited nd enqueue it
  47.         for (auto itr = adj[u].begin();
  48.                 itr != adj[u].end(); itr++)
  49.         {
  50.             if (!visited[*itr])
  51.             {
  52.                 // Assign Component Number to all the
  53.                 // reachable nodes
  54.                 visited[*itr] = componentNum;
  55.                 queue.push(*itr);
  56.             }
  57.         }
  58.     }
  59.     return reachableNodes;
  60. }

  61. // Display all the Reachable Nodes from a node 'n'
  62. void displayReachableNodes(int n,
  63.             unordered_map <int, vector<int> > m)
  64. {
  65.     vector<int> temp = m[n];
  66.     for (int i=0; i<temp.size(); i++)
  67.         cout << temp[i] << " ";

  68.     cout << endl;
  69. }

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

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

  80.     // Map to store list of reachable Nodes for a
  81.     // given node.
  82.     unordered_map <int, vector<int> > m;

  83.     // Initialize component Number with 0
  84.     int componentNum = 0;

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

  90.         // Visit all the nodes of the component
  91.         if (!visited[u])
  92.         {
  93.             componentNum++;

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

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

  104. // Driver program to test above functions
  105. int main()
  106. {
  107.     // Create a graph given in the above diagram
  108.     int V = 7;
  109.     Graph g(V);
  110.     g.addEdge(1, 2);
  111.     g.addEdge(2, 3);
  112.     g.addEdge(3, 4);
  113.     g.addEdge(3, 1);
  114.     g.addEdge(5, 6);
  115.     g.addEdge(5, 7);

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

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

  121.     findReachableNodes(g, arr, n);

  122.     return 0;
  123. }
复制代码
Output:
  1. Reachable Nodes from 2 are
  2. 1 2 3 4
  3. Reachable Nodes from 4 are
  4. 1 2 3 4
  5. Reachable Nodes from 5 are
  6. 5 6 7
复制代码
  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.
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
有些的时候,正是为了爱才悄悄躲开.躲开的是身影,躲不开的却是那份默默的情怀。
回复 支持 反对

使用道具 举报

我要投稿

回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表