算法训练1-day42-图论

20 阅读1分钟
  1. 98. 可达路径

图论开始,主要熟悉邻接表和邻接矩阵建图,以及基础的DFS和BFS

  • dfs是可一个方向去搜,不到黄河不回头,直到遇到绝境了,搜不下去了,再换方向(换方向的过程就涉及到了回溯)。
  • bfs是先把本节点所连接的所有节点遍历一遍,走到下一个节点的时候,再把连接节点的所有节点遍历一遍,搜索方向更像是广度,四面八方的搜索过程。

AC代码:

#include 
#include 
#include 
#include 

using namespace std;

class EdgeNode {
public:
  EdgeNode() { next = -1; }
  EdgeNode(int next) { this->next = next; }

  const int GetNext() { return next; }

private:
  int next;
};

class MyGraph {
public:
  MyGraph() {}

  MyGraph(int n_vertex) {
    vertexes = vector(n_vertex);
    for (int i = 1; i <= n_vertex; i++) {
      vertexes[i - 1] = i;
    }
  }
  void AddVertex(int vertex) { vertexes.push_back(vertex); }

  void AddEdge(int from, int to) {
    if (edges.find(from) == edges.end()) {
      edges[from] = list();
    }
    ////无向图
    // if (edges.find(to) == edges.end()) {
    //	edges[to] = list();
    //}

    edges[from].push_back(new EdgeNode(to));
    // edges[to].push_back(new EdgeNode(from));
  }

  ~MyGraph() {
    for (auto item : edges) {
      for (EdgeNode *edge : item.second) {
        delete edge;
      }
    }
  }

  list GetEdges(int vertex) { return edges[vertex]; }

  vector> dfs(int from, int target) {
    vector> res;
    _dfs(res, from, target, vector());
    return res;
  }

private:
  void _dfs(vector> &res, int from, int to, vector path) {
    path.push_back(from);
    if (from == to) {
      res.push_back(path);
      return;
    }

    for (auto edge : edges[from]) {
      _dfs(res, edge->GetNext(), to, path);
    }
  }

private:
  vector vertexes;
  unordered_map> edges;
};

int main() {
  int n = 0, m = 0;
  cin >> n >> m;

  MyGraph graph(n);

  int from = 0, to = 0;
  for (int i = 0; i < m; i++) {
    cin >> from >> to;
    graph.AddEdge(from, to);
  }

  vector> res = graph.dfs(1, n);
  if (res.empty()) {
    cout << -1 << endl;
  }
  for (auto item : res) {
    for (int i = 0; i < item.size(); i++) {
      cout << item[i];
      if (i != item.size() - 1) {
        cout << &#34; &#34;;
      }
    }
    cout << endl;
  }

  return 0;
}