简单的bfs(最短路径)c++

#include<iostream>
#include<queue>
#include<vector>
using namespace std;
const int height = 5;
const int width = 5;
class Node
{
public:
    int x;
    int y;
    Node *prenode;
    Node(int x1, int y1, Node *prenode1=NULL) :x(x1), y(y1), prenode(prenode1){};
};
int matrix[height][width] = {
    0, 0, 0, 0, 1,
    0, 1, 0, 1, 0,
    0, 1, 0, 0, 0,
    0, 1, 0, 1, 0,
    0, 0, 0, 1, 0,
};
vector<Node*> vnode;     //存放节点是否访问过的
queue<Node*> qnode;      
//访问
void visit(int x, int y, Node* p)
{
    Node* pr = new Node(x,y,p);
    matrix[x][y] = 2;               
    qnode.push(pr);
}

void bfs()
{
    int dist[4][2] = { {0,-1}, {0,1}, {-1,0}, {1,0} };   //上下左右
    Node* p = NULL;
    Node* head = new Node(0,0,p);
    qnode.push(head);
    while (!qnode.empty())
    {
        Node *p = qnode.front();
        vnode.push_back(p);
        qnode.pop();
        if (p->x == height - 1 && p->y == width - 1)
            break;
        for (int i = 0; i < 4; i++)
        {
            
            if (p->x+dist[i][0]>=0 &&p->x+dist[i][0]<height&&
                p->y+dist[i][1] >= 0&&p->y+dist[i][1]<width && matrix[p->x+dist[i][0]][p->y+dist[i][1]] == 0)
                visit(p->x+dist[i][0], p->y+dist[i][1], p);
        }
        
    }

}
void printPath()  //打印路径
 {
        
         Node *p = vnode[vnode.size() - 1];

        while (p != NULL)
             {
                 cout << "(" << p->x << "," << p->y << ")";
                 if (p->prenode != NULL)
                     cout << "<-";
                 p = p->prenode;
                 
            }
         cout<<endl;
         }
void destroy()  //销毁节点
{
    for (int i = 0; i < vnode.size(); i++)
    {
        delete vnode[i];
    }
}
int main()
{
    bfs();
    printPath();
    destroy();
    system("pause");
    return 0;
}

 

转载于:https://www.cnblogs.com/dxxiaoxin-xidian/p/7356336.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值