分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请轻击人工智能教程大家好!欢迎来到我的网站! 人工智能被认为是一种拯救世界、终结世界的技术。毋庸置疑,人工智能时代就要来临了,科… 继续阅读 前言
https://www.captainai.net/troubleshooter
/*
* 问题:求解迷宫问题。
*
* 分析:
* 方法:BFS广度优先搜索。
* 算法:
* 1、将起点入队。
* 2、队首结点可扩展的点入队;如果没有可扩展的点,将队首结点出队。
* 3、重复第2步,直到到达目标位置或者队列为空。
* 注:BFS搜索到的结果一定是最短的。BFS运用到了队列。
*
* Maze_BFS.cpp - by LiveEveryDay
*/
#include <queue>
using namespace std;
int startX, startY, endX, endY, row, col;
int a[100][100]; // 1表示空地,2表示障碍物。
int v[100][100]; // 0表示未访问,1表示已访问。
struct point {
int x;
int y;
int step;
};
queue<point> q; // 申请队列
int dx[4] = {0, 1, 0, -1}; // 四个方向(右、下、左、上)在X轴的偏移量。
int dy[4] = {1, 0, -1, 0}; // 四个方向(右、下、左、上)在Y轴的偏移量。
void bfs() {
point start;
start.x = startX;
start.y = startY;
start.step = 0;
q.push(start);
v[startX][startY] = 1;
int flag = 0;
while (!q.empty()) {
int x = q.front().x;
int y = q.front().y;
if (x == endX && y == endY) {
flag = 1;
printf("The min step is: %d", q.front().step);
break;
}
// 顺时针试探
for (int i = 0; i <= 3; i++) {
int tx = x + dx[i];
int ty = y + dy[i];
if (a[tx][ty] == 1 && v[tx][ty] == 0) {
// 入队
point t;
t.x = tx;
t.y = ty;
t.step = q.front().step + 1;
q.push(t);
v[tx][ty] = 1;
}
}
q.pop(); // 拓展完成,将队首元素出队。
}
if (flag == 0) {
printf("No solution!");
}
}
int main() {
printf("Input row and col:\n");
scanf("%d%d", &row, &col);
printf("Input the map:\n");
for (int x = 1; x <= row; x++) {
for (int y = 1; y <= col; y++) {
scanf("%d", &a[x][y]); // 1表示空地,2表示障碍物。
}
}
printf("Input start position:\n");
scanf("%d%d", &startX, &startY);
printf("Input end position:\n");
scanf("%d%d", &endX, &endY);
bfs();
return 0;
}
// ------ Input ------
/*
Input row and col:
5 4
Input the map:
1 1 2 1
1 1 1 1
1 1 2 1
1 2 1 1
1 1 1 2
Input start position:
1 1
Input end position:
4 3
*/
// ------ Output ------
/*
The min step is: 7
*/

本文介绍了一种使用广度优先搜索(BFS)解决迷宫最短路径问题的方法。通过将起点加入队列,并逐步扩展到相邻节点,最终找到从起点到终点的最短路径。适用于初学者学习算法。
1115

被折叠的 条评论
为什么被折叠?



