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

问题描述 投票:0回答:2

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

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

我很感激如何解决这个问题的指导。我有一些问题:

  1. 我是否将矩阵从文本文件保存到我的程序中作为常规矩阵?
  2. 一旦我读完文本文件以显示搜索结果,该怎么办?
c++ matrix depth-first-search breadth-first-search adjacency-matrix
2个回答
1
投票

答案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
投票
  1. http://www.geeksforgeeks.org/depth-first-traversal-for-a-graph/

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

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

步骤1:维护一组布尔值,以保存是否访问了节点。

第2步:实现队列

步骤3:从任何元素开始并将其推入队列并将其标记为已访问。 Step4:在循环中将队列中的顶部元素出列队列。它是x

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

执行step4直到队列为空..

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

如果我找时间,我会解释dfs

© www.soinside.com 2019 - 2024. All rights reserved.