在邻接矩阵上应用广度和深度优先搜索

Apply breadth and depth first search on an adjacency matrix?

本文关键字:深度优先搜索 应用 邻接矩阵      更新时间:2023-10-16

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

我知道宽度优先使用FIFO队列,深度优先使用LIFO堆栈。我能够得到这些搜索时,我有图表,手动。我只是不确定如何在计算机上处理这个问题,并在c++上使用矩阵。

如果你能指导我如何解决这个问题,我会很感激的。我有一些问题:
  1. 我是否将矩阵从文本文件保存到我的程序中作为常规矩阵?
  2. 一旦我读了文本文件来显示搜索结果,该怎么办?

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
                }
            }
        }
    }
  1. http://www.geeksforgeeks.org/depth-first-traversal-for-a-graph/
http://www.geeksforgeeks.org/breadth-first-traversal-for-a-graph/

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

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

Step2:实现队列

Step3:从任意元素开始,将其推入队列并标记为已访问。目的:在循环中取消队列顶部元素的队列设置为x

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

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

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

如果我有时间我会解释的