C 中矩阵的BFS(广度首次搜索)

BFS (breadth first search) of matrix in C++

本文关键字:搜索 BFS      更新时间:2023-10-16

我正在处理以下任务:

编写用于广度的首次搜索的软件,从a到b,c,d,e,fand比较算法的特征。

这些字母放在矩阵中,该矩阵由class Matrix制成。形成的矩阵的每个元素都是class Node的对象,能够存储信息bool visited,位置在int r, int k(授权行,列)和char value

我什至能够在矩阵中找到一个角色并返回其位置,但是我不知道如何通过广度第一次搜索从角色到角色进行搜索。我的最后一次尝试是在BFS.cpp中,但是我看到了我所做的那种使用,而不是。

我该如何从字符的矩阵中从char a到char b?

以下是代码:(对不起,金额很大)

main.cpp

#include <iostream>
#include "Matrix.h"
#include "BFS.h"
using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    {
    //make matrix
    Matrix matrix1 ;
    cout<<"matrix1"<<endl<<matrix1<<endl;
    matrix1.findNode('A');
    matrix1.findNode('B');
    BFS bfs1('A',matrix1,0) ;
    }
    cout << "Bye world!" << endl;
    return 0;
}

matrix.h

#ifndef MATRIX_H
#define MATRIX_H
#include "Node.h"
#include <iostream>
using namespace std ;
class Matrix
{
    int size = 6 ;
    Node** matrix ;
    public:
        Matrix();
        virtual ~Matrix();
        friend ostream& operator<<(ostream& out, Matrix &p) ;
        Node& findNode(char _A) ;

    protected:
    private:
};
#endif // MATRIX_H

matrix.cpp

#include "Matrix.h"
Matrix::Matrix()
{
    //ctor
    matrix = new Node*[size];
    for(int r=0; r<size; r++){
            matrix[r] = new Node[size];
    }
    // correct positions of nodes
    for(int r=0; r<size; r++)
    {
        for(int k = 0; k<size;k++)
        {
            matrix[r][k].setPos(r,k) ;
        }
    }
    // Now set characters A t/m F in fixed position
    matrix[2][2].setValue('A') ;
    matrix[0][0].setValue('B') ;
    matrix[0][2].setValue('C') ;
    matrix[4][1].setValue('D') ;
    matrix[5][5].setValue('E') ;
    matrix[5][0].setValue('F') ;
}
Matrix::~Matrix()
{
    //dtor
    for(int r=0; r<size; r++){
        delete [] matrix[r];
    }
    delete [] matrix ;
}
ostream& operator<<(ostream& out, Matrix &p)
{
    for(size_t r=0; r<p.size; r++)
    {
        for(size_t k = 0; k<p.size;k++)
        {
            out<<p.matrix[r][k].getValue()<<"  " ;
        }
        out<<endl ;
    }
    out<<"____________________________"<<endl;
}
Node& Matrix::findNode(char _A)
{
    bool found = false ;
    Node ans ;
    for(int r=0; r<size; r++)
    {
        for(int k = 0; k<size;k++)
        {
            if( matrix[r][k].getValue() == _A )
            {
                ans = matrix[r][k] ;
                found = true ;
                break ;
            }
        }
    }
    cout<<"Search for "<<_A<<" results:";
    if (found)
    {
        cout<<" found: "<<ans<<endl ;
        return ans ;
    }
    else
    {
        cout<<" not found."<<endl ;
    }
}

node.h

#ifndef NODE_H
#define NODE_H
#include <iostream>
using namespace std;
class Node // ctor, dtor, operator=, operator<<, setPos, setState, setValue
{
    int r ; int k ; //row nr and column nr,  because used in BFS
    bool visited ;
    char value ;
    public:
        Node(int _r = 0, int _k = 0,char _value = '_', bool _visited = false);
        virtual ~Node();
        Node& operator=(const Node &p);
        friend ostream& operator<<(ostream& out, Node &p);
        void setPos(int _r, int _k);
        void setState(bool _visited);
        void setValue(char _value);
        char getValue();
    protected:
    private:
};

#endif // NODE_H

node.cpp

#include "Node.h"
// all this code is integrated in Node.h
Node::Node(int _r, int _k,char _value, bool _visited)
{
    //ctor
    // defaults specified in Node.h : 0 0 _ false
    r = _r ; k = _k ; value = _value ; visited = _visited ;
}
Node::~Node()
{
    //dtor
}
Node& Node::operator=(const Node &p)
{
    r = p.r ; k = p.k ; value = p.value ; visited = p.visited ;
};
ostream& operator<<(ostream& out, Node &p)
{
    out<<"["<<p.r<<"]["<<p.k<<"] has value '"<<p.value<<"'" ;
};
void Node::setPos(int _r, int _k)
{
    r = _r ; k = _k ;
};
void Node::setState(bool _visited)
{
    visited = _visited ;
};
void Node::setValue(char _value)
{
    value = _value ;
};
char Node::getValue()
{
    return value ;
};

bfs.h

#ifndef BFS_H
#define BFS_H
#include <vector>
#include "Matrix.h"
#include "Node.h"
    //BFS algorithm:
    /*
    Step 1: Push the root node in the Stack.
Step 2: Loop until stack is empty.
Step 3: Peek the node of the stack.
Step 4: If the node has unvisited child nodes, get the unvisited child node, mark it as traversed and push it on stack.
Step 5: If the node does not have any unvisited child nodes, pop the node from the stack.
    */
    // object of class BFS should be the queue of nodes to be checked
//class Node ; class Matrix ;
class BFS
{
    //queue<Node> queueNodes;
    vector<Node> fronts ;
    public:
        BFS(char _start, Matrix _matrix, int _distance);
        virtual ~BFS();
        friend bool& isPresent(vector<Node> _vector , Node& _n) ;
    protected:
    private:
};
#endif // BFS_H

bfs.cpp

#include "BFS.h"

BFS::BFS(char _start, Matrix _matrix, int _distance)
{
    //ctor; form que
    //determine startpoint
    vector<Node> newfronts ;
    fronts.push_back(_matrix.findNode(_start)) ;
    cout<<"BFS made"<<endl;
    for(int i = 0 ; i < _distance ; i++)
    {
        // determine the new fronts
        for(size_t f = 0 ; f < sizeof(fronts) ; f++)
        {
            // do only if new item is not in newfronts OR fronts yet AND if does not exceed matrix dimensions
            if ( fronts[f].r - 1 !< 0 )
            {
                Node up = _matrix[fronts[f].r - 1][fronts[f].k] ;
                if ( ! isPresent(fronts, up) && ! isPresent(newfronts, up) )
                {
                    newfronts.push_back(up) ;
                }
            }
            if ( fronts[f].r + 1 !> _matrix.size )
            {
                Node down = _matrix[fronts[f].r + 1][fronts[f].k] ;
                newfronts.push_back(down) ;
            }
            if ( fronts[f].k + 1 !> _matrix.size )
            {
                Node right = _matrix[fronts[f].r][fronts[f].k + 1] ;
                newfronts.push_back(right) ;
            }
            if ( fronts[f].k - 1 !< 0 )
            {
                Node left = _matrix[fronts[f].r][fronts[f].k - 1] ;
                newfronts.push_back(left) ;
            }
       }
    }
}
BFS::~BFS()
{
    //dtor
}
bool isPresent(vector<Node> _vector , Node& _n)
{
    bool present = false ;
    for(size_t i = 0 ; i < sizeof(_vector) ; i++)
    {
        if( _vector[i] == _n)
            present = true ;
    }
    return present ;
}

如果您一直在这里进行管理,已经感谢您的时间。: - )

您是正确的,您需要一个排队进行广度优先搜索,以及用于深度优先搜索的堆栈,这是两者之间的关键差异。

首先,我会亲自将功能添加到您的矩阵中,名为get nekinbors以获取一个单元格的邻居,然后是这样的代码bf。

使用它可以简单地编写BFS函数。

BFS::BFS(char _start, char goal, Matrix _matrix, int _distance)
{
    Queue<Node> Frontier ;
    Frontier.push_back(_matrix.findNode(_start));
    cout << "BFS beginning" << endl;
    int count = 0;
    while(count < _distance)
    {
        Node lCurrent = Frontier.front();
        Frontier.pop();
        if( lCurrent.getValue() == goal )
        {
            cout << "Goal Found" << endl;
            cout << "Number of steps taken: "  << count << endl;
            return;
        }
        vector<node> currentNeighbors() = lCurrent.getNeighbors();
        for (size_t i = lNeighbours.size(); i > 0; i--)
        {
            Frontier.push(lNeighbours[i-1]);
        }
    }  
    cout << "Maximum distance of " << _distance << " with no    solution found, BFS aborted." << endl;

}

您可能需要对其进行一些调整以适合您的程序,并注意该解决方案无法维护访问的节点列表,因此您可以跳过一些已经评估的节点。