# 迷宫问题、最短路（BFS，DFS）

``````#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' || vis[nx][ny]==1)
continue;   //下标越界或者访问过或者是障碍物
q.push(node(nx, ny, now.cnt + 1));
vis[nx][ny] = 1;
path[nx][ny] = i;
}
}
return -1;
}

//深度优先搜索
void dfs(node s, node& t) {
vis[s.x][s.y] = 1;
if (s.x == t.x && s.y == t.y) {
t.cnt = s.cnt;
return;
}

for (int i = 0; i < 4; ++i) {
int nx = s.x + dx[i];
int ny = s.y + dy[i];
if (nx<0 || nx >= m || ny<0 || ny >= n || map[nx][ny] == '0' || vis[nx][ny] == 1)
continue;   //下标越界或者访问过或者是障碍物
vis[nx][ny] = 1;
path[nx][ny] = i;
dfs(node(nx, ny, s.cnt + 1),t);
}

}

//打印路径
void printPath(node s, node t) {
stack<node> tmp;
tmp.push(t);
int x = t.x, y = t.y;
while (!(x == s.x && y == s.y)) {
int i = path[x][y];
x = x - dx[i];
y = y - dy[i];
tmp.push(node(x,y));
}

tmp.pop();
cout << "(" << s.x << "," << s.y << ")";
while (!tmp.empty()) {
node k = tmp.top();
tmp.pop();
cout << "-->" << "(" << k.x << "," << k.y << ")";
}
cout << endl;
}

int main()
{
while (cin >> m >> n) {
//输入地图
for (int i = 0; i < m; ++i) {
cin >> map[i];
}

node s, t;//起点、终点
cin >> s.x >> s.y >> t.x >> t.y;

//dfs(s, t);
cout << bfs(s,t) << endl;

printPath(s, t);
}

return 0;
}``````

原文作者：BFS
原文地址: https://blog.csdn.net/wangchao7281/article/details/76578142
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。