【BFS】BFS模板(#include<queue>)

本文介绍了一个使用广度优先搜索(BFS)算法解决迷宫最短路径问题的C++实现。通过定义结构体节点来存储坐标及步数,并利用队列进行遍历,实现了从起点到终点的最短路径计算。

具体解释看代码批注。


#include<iostream>
#include <queue>
#include <string>
using namespace std;

int mp[6][6];
int vis[6][6];//用来标记是否走过的点;
int n,m;
int d[4][2] = {1,0,0,1,-1,0,0,-1};//方向,上下左右

struct node
{
  int x,y,step;
};

int bfs()
{
  memset(vis,0,sizeof(vis));

  queue<node>q;

  node s,e;

  s.x = 0;//初始化坐标;
  s.y = 0;
  s.step = 0;//开始时走过的步数为0;
  vis[s.x][s.y] = 1;//注意不要遗漏标记第一个点;

  q.push(s);//加入起始点

  while(!q.empty())//队列不为空;
    {
      e = q.front();//元素依次入队;
      q.pop();//爆掉第一个元素;

      if(e.x==4 && e.y==4)
      {
         return e.step;//走到头就over;
      }

      for(int i=0; i<4; i++)
        {
          s.x = e.x + d[i][0];//元素加入方向;
          s.y = e.y + d[i][1];
          s.step = e.step + 1;//步数加1;

          if(s.x<0 || s.x>n-1 || s.y<0 || s.y>m-1 ||
             mp[s.x][s.y]==1 || vis[s.x][s.y]==1) continue;//判断是否出界;

             vis[s.x][s.y] = 1;

             q.push(s);
          }
    }

    return -1;
}

int main()
{
  n=m=5;
	int i,j;
  for(i=0; i<n; i++)
    {
      for(j=0; j<m; j++)
        {
          scanf("%d",&mp[i][j]);
        }
    }

  printf("%d\n",bfs());

  return 0;
}


在C++中,如果你不想使用`<vector>`和`<queue>`这两个头文件,可以不用它们来实现一些基础操作,比如数组或者手动管理堆栈。例如,你可以直接使用数组来代替队列,或者使用循环和指针来模拟队列的行为。这里是一个简化的邻接表表示无向图的例子,不使用`std::queue`: ```cpp #include <iostream> // 定义邻接列表节点 struct Node { int destination; Node* next; }; // 自己实现的一个简单的队列 class SimpleQueue { private: Node* front; Node* rear; public: SimpleQueue() : front(nullptr), rear(nullptr) {} ~SimpleQueue() { clear(); } // 入队 void enqueue(int value) { Node* newNode = new Node{value, nullptr}; if (rear == nullptr) { front = rear = newNode; } else { rear->next = newNode; rear = newNode; } } // 出队 int dequeue() { if (front == nullptr) { throw std::runtime_error("Queue is empty"); } Node* temp = front; front = front->next; delete temp; if (front == nullptr) { rear = nullptr; } return temp->destination; } // 清空队列 void clear() { while (front != nullptr) { Node* temp = front; front = front->next; delete temp; } rear = nullptr; } }; // 邻接列表表示无向图 class AdjListGraphWithoutVector { private: int numVertices; Node** adjList; public: AdjListGraphWithoutVector(int vertices) : numVertices(vertices), adjList(new Node*[vertices]) { for (int i = 0; i < vertices; ++i) adjList[i] = nullptr; } ~AdjListGraphWithoutVector() { for (int i = 0; i < numVertices; ++i) delete[] adjList[i]; delete[] adjList; } // 添加边 void addEdge(int src, int dest) { Node* newNode = new Node{dest, adjList[src]}; if (adjList[src] == nullptr) { adjList[src] = newNode; } else { Node* curr = adjList[src]; while (curr->next != nullptr) { curr = curr->next; } curr->next = newNode; } } // 自己实现的BFS void breadthFirstSearch(int start) { SimpleQueue queue; bool* visited = new bool[numVertices]{false}; queue.enqueue(start); visited[start] = true; while (!queue.isEmpty()) { int current = queue.dequeue(); std::cout << current << " "; for (Node* node = adjList[current]; node != nullptr; node = node->next) { int neighbor = node->destination; if (!visited[neighbor]) { queue.enqueue(neighbor); visited[neighbor] = true; } } } delete[] visited; } }; int main() { int vertices = 5; AdjListGraphWithoutVector graphWithoutVector(vertices); // 添加边... graphWithoutVector.addEdge(0, 1); graphWithoutVector.addEdge(0, 4); // 示例 // 遍历 std::cout << "Breadth First Search: "; graphWithoutVector.breadthFirstSearch(0); return 0; } ``` 在这个例子中,我们自定义了一个`SimpleQueue`类用于模拟队列的功能,同时也手动分配和释放内存。注意,这种方法的效率和复杂性相对较低,因为需要手动管理内存,且没有像`std::queue`那样的内置优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值