【问题标题】:Apply breadth and depth first search on an adjacency matrix?在邻接矩阵上应用广度和深度优先搜索?
【发布时间】:2016-11-18 17:56:43
【问题描述】:

我得到了这个邻接矩阵,我必须从文本文件中读取它,并且应该返回广度优先和深度优先读取的结果。

我知道广度优先使用 FIFO 队列,而深度优先使用 LIFO 堆栈。当我有图表时,我可以手动获得这些搜索。我只是不确定如何在计算机上解决这个问题,并在 C++ 上使用矩阵。

我希望得到有关如何解决此问题的指导。 我有一些问题:

  1. 是否将文本文件中的矩阵作为常规矩阵保存到程序中?
  2. 读取文本文件以显示搜索结果后该怎么办?

【问题讨论】:

    标签: c++ matrix depth-first-search breadth-first-search adjacency-matrix


    【解决方案1】:

    ANS 1: 是的,最好将文本文件中的输入读入常规矩阵。

    void MyGraph::csv_import()
        {
            int temp, i=0;
            string parsed;
            fstream file("input.csv");
            while (getline(file, parsed, ',')) {
                temp = stoi(parsed);
                arr[i/10][i%10] = temp; //10 x 10 Matrix
                i++;
            }
        }
    

    ANS 2:选择一个起始节点,调用BFS显示搜索结果。例如(在我的情况下)

    void MyGraph::BFS(int v)
        {
            memset(visited, false, sizeof(visited);
            QQ.push(v);                         //push the starting vertex into queue
            visited[v] = true;                  //mark the starting vertex visited
            while (!QQ.empty())                 //until queue is not empty
            {
                v = QQ.front();                 //assign v the vertex on front of queue
                cout << v << "  ";              //print the vertex to be popped
                QQ.pop();                       //pop the vertex on front
                for (int c = 0; c< V; c++)      //V is the number of nodes
                {
                     //M[i][j] == 1, when i,j are connected
                    if (M[v][c] == 1 && visited[c] == false) 
                    {                           //if vertex has edge and is unvisited
                        QQ.push(c);             //push to the queue
                        visited[c] = true;      //mark it visited
                        Path[c] = p;            //assign the path length
                    }
                }
            }
        }
    

    【讨论】:

      【解决方案2】:
      1. 是的
      2. http://www.geeksforgeeks.org/depth-first-traversal-for-a-graph/

      http://www.geeksforgeeks.org/breadth-first-traversal-for-a-graph/

      BFS: 注意:对于无向图,扫描矩阵的上三角形或下三角形就足够了。 对于有向图,应考虑整个矩阵。

      Step1:维护一个布尔值数组,用于保存节点是否被访问。

      Step2:实现一个队列

      Step3:从任意元素开始,将其推入队列并将其标记为已访问。 第4步: 在一个循环中 将队列中的顶部元素出列..让它成为 x

      对于x的所有未访问的邻居..将它们推入队列并将它们标记为已访问。

      执行步骤 4 直到队列为空..

      图遍历顺序是在将元素推入队列时给出的。

      如果我有时间我会解释 dfs

      【讨论】:

      • 建议添加链接摘要,否则链接失效后您的答案将毫无用处。
      • 我现在就这么做..很好
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      相关资源
      最近更新 更多