博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
BFS——走迷宫的最小步数
阅读量:4216 次
发布时间:2019-05-26

本文共 1069 字,大约阅读时间需要 3 分钟。

在这里插入图片描述

在这里插入图片描述

#include
#include
#include
using namespace std;const int maxn = 100;struct node{
int x, y; int step;}S, T, Node;int n, m; char maze[maxn][maxn]; // 迷宫信息 bool inq[maxn][maxn] = {
false};int X[4] = {
0, 0, 1, -1};int Y[4] = {
1, -1, 0, 0}; // 增量数组bool test(int x, int y){
if(x >= n || x < 0 || y >= m || y < 0) return false; if(maze[x][y] == '*') return false; if(inq[x][y] == true) return false; return true;} int BFS(){
queue
Q; Q.push(S); while(!Q.empty()) {
node top = Q.front(); Q.pop(); if(top.x == T.x && top.y == T.y) return top.step; for(int i = 0; i < 4; i++) {
int newX = top.x + X[i]; int newY = top.y + Y[i]; if(test(newX, newY)) {
Node.x = newX; Node.y = newY; Node.step = top.step + 1; Q.push(Node); inq[newX][newY] = true; } } } return -1;}int main(){
scanf("%d%d", &n, &m); for(int i = 0; i < n; i++) {
scanf("%s", maze[i]); } scanf("%d%d%d%d", &S.x, &S.y, &T.x, &T.y); S.step = 0; printf("%d", BFS()); return 0;}

在这里插入图片描述

转载地址:http://shtmi.baihongyu.com/

你可能感兴趣的文章
腾讯云服务器ftp部署及文件上传
查看>>
Python堆排序
查看>>
Centos 6.4 python 2.6 升级到 2.7
查看>>
Python哈希查找,构建简单哈希表
查看>>
Python快速排序
查看>>
C++ primer plus笔记整理 01
查看>>
C++ primer plus笔记整理 02
查看>>
C++ primer plus笔记整理 03
查看>>
C++ primer plus笔记整理 04
查看>>
C++ primer plus笔记整理 05
查看>>
socket05---recv && send使用,回射客户端
查看>>
socket编程---fgets和fputs函数使用理解
查看>>
socket06---僵尸进程的避免
查看>>
371. Sum of Two Integers
查看>>
并查集详解 (转)
查看>>
226. Invert Binary Tree
查看>>
100. Same Tree
查看>>
Python:使用threading模块实现多线程(转)
查看>>
237. Delete Node in a Linked List
查看>>
203. Remove Linked List Elements
查看>>