Advertisement
kuathadianto

Delete Node from Graph

Jul 1st, 2015
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. // Kuat Hadianto
  2. // 1.7.2015
  3.  
  4. #include <iostream>
  5. #include <map>
  6. #include <vector>
  7. using namespace std;
  8.  
  9. // Delete node from a graph
  10. map<int, vector<int> > deleteNode(map<int, vector<int> > graph, int toBeDeleted) {
  11.     map<int, vector<int> > output;
  12.  
  13.     // Create a new graph without including the node "toBeDeleted"
  14.     for (map<int, vector<int> >::iterator it = graph.begin(); it != graph.end(); it++) {
  15.         if (it->first != toBeDeleted) {
  16.             for (int i = 0; i < it->second.size(); i++) {
  17.                 if (it->second[i] != toBeDeleted) {
  18.                     output[it->first].push_back(it->second[i]);
  19.                 }
  20.             }
  21.         }
  22.     }
  23.  
  24.     return output;
  25. }
  26.  
  27. // Print graph
  28. void print(map<int, vector<int> > graph) {
  29.     for (map<int, vector<int> >::iterator it = graph.begin(); it != graph.end(); it++) {
  30.         cout << it->first << ": ";
  31.         for (int i = 0; i < it->second.size(); i++) {
  32.             cout << it->second[i] << " ";
  33.         }
  34.         cout << endl;
  35.     }
  36. }
  37.  
  38. int main() {
  39.     map<int, vector<int> > graph;
  40.     graph[1].push_back(2);
  41.     graph[1].push_back(3);
  42.  
  43.     graph[2].push_back(1);
  44.     graph[2].push_back(3);
  45.     graph[2].push_back(4);
  46.  
  47.     graph[3].push_back(1);
  48.     graph[3].push_back(2);
  49.  
  50.     graph[4].push_back(2);
  51.  
  52.     map<int, vector<int> > afterDelete = deleteNode(graph, 3);
  53.  
  54.     print(graph);
  55.     cout << endl;
  56.     print(afterDelete);
  57.  
  58.     system("PAUSE");
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement