#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
const int N = 100;
char map[N][N];
bool vis[N][N] = {0}; //访问记录
int path[N][N]; //记录路径 0、1、2、3分别代表上下左右
int dx[4] = {-1,1,0,0}; //上下左右移动
int dy[4] = {0,0,-1,1};
int m, n; //行数、列数
//地图实例,1为可行,0为不可行
/* 11101
10111
10010
11110 */
struct node {
int x, y;
int cnt;//起点到此点的最短路径长度
node():cnt(0) {}
node(int xx, int yy, int c=0) :x(xx), y(yy), cnt(c) {}
};
//广度优先搜索
int bfs(node s, node t) {
queue<node> q;
q.push(s);
vis[s.x][s.y] = 1;
while (!q.empty()) {
node now = q.front();
q.pop();
if (now.x == t.x && now.y == t.y)
return now.cnt;
for (int i = 0; i < 4; ++i) {
int nx = now.x + dx[i];
int ny = now.y + dy[i];
if (nx<0 || nx>=m || ny<0 || ny>=n || map[nx][ny]=='0' || vi
迷宫问题、最短路(BFS,DFS)
最新推荐文章于 2024-01-17 22:57:56 发布
本文介绍了解决迷宫问题的两种经典算法——广度优先搜索(BFS)和深度优先搜索(DFS),并提供了C++实现。通过BFS求解起点到终点的最短路径,并展示如何打印路径。
摘要由CSDN通过智能技术生成