olexander_dan

Untitled

May 6th, 2019
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. #include "vList.h"
  5. #include "grRepres.h"
  6.  
  7. using namespace std;
  8.  
  9. void GrA::setisDir(bool d) { isDir = d; }
  10.  
  11. GrMA::~GrMA() {
  12.     if (E != nullptr) {
  13.         for (size_t l = 0; l < n; ++l) {
  14.             delete[] E[l];
  15.             E[l] = nullptr;
  16.         }
  17.         delete[] E;
  18.         E = nullptr;
  19.     }
  20. }
  21.  
  22. bool GrMA::create(size_t _n) {
  23.     // deletes all the information in previous 2D array
  24.     if (E != nullptr) {
  25.         for (size_t l = 0; l < n; ++l) {
  26.             delete[] E[l];
  27.             E[l] = nullptr;
  28.         }
  29.         delete[] E;
  30.         E = nullptr;
  31.     }
  32.  
  33.     // creates new 2D matrix
  34.     n = _n;
  35.     E = new(nothrow) bool* [n] {};
  36.     if (E != nullptr) {
  37.         for (size_t i = 0; i < n; ++i) {
  38.             E[i] = new(nothrow) bool [n] {};
  39.             if (E[i] == nullptr)
  40.                 break;
  41.         }
  42.     }
  43.     return (E != nullptr);
  44. }
  45.  
  46. bool GrMA::addArc(size_t v, size_t w) {
  47.     E[v][w] = true;
  48.     if (!isDir)
  49.         E[w][v] = true;
  50.     ++m;
  51.     return true;
  52. }
  53.  
  54. VList GrMA::neighbors(size_t i) {
  55.     VList L(n);
  56.     for (int j = 0; j < n; ++j) // check entire matrix
  57.         if (E[i][j] != false)
  58.             L.add(j);
  59.     return L;
  60. }
  61.  
  62. VList GrA::dfs() {
  63.     VList L(n);
  64.     bool* visited = new(nothrow) bool[n];
  65.     if (visited != nullptr) {
  66.         size_t v;
  67.         for (v = 0; v < n; ++v)
  68.             visited[v] = false;
  69.         for (v = 0; v < n; ++v)
  70.             if (!visited[v])
  71.                 dfsr(v, L, visited);
  72.     }
  73.     delete[]visited;
  74.     return L;
  75. }
  76.  
  77. void GrMA::dfsr(size_t v, VList& L, bool*& visited) {
  78.     L.add(v); visited[v] = 1;
  79.     for (size_t w = 0; w < n; ++w)
  80.         if (E[v][w]) // w adjacent with v  
  81.             if (!visited[w]) // і isn't visited
  82.                 dfsr(w, L, visited);
  83. }
Advertisement
Add Comment
Please, Sign In to add comment