给定一个n*m大小的迷宫,其中*代表墙,而.代表平地,S代表起点,T代表终点。移动过程中,如果当前位置是(x,y)下标从0开始,且每次只能上下左右(x,y+1)、(x,y-1)、(x-1,y)、(x+1,y)四个位置的平地,求起点S到终点T的最小步数。
void BFS_dfs(int step,int x,int y)此函数是bfs改为dfs的函数:
#include "stdafx.h"
#include
#include
#include
#include
using namespace std;
//变量声明
const int maxn = 1000;
struct node {
int x, y; //位置x,y
int step; //step为起点S到终点T的最小步数
}S, T, Node; //S为起点,T为终点,Node为临时结点
int n, m;
char maze[maxn][maxn]; //迷宫信息
bool inq[maxn][maxn] = { false }; //记录位置(x,y)是否已入队
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.push(S);
inq[S.x][S.y] = true;
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;
//printf("%d\n", Node.step);
q.push(Node);
inq[newX][newY] = true;
}
}
}
return -1;
}
int min_step = -1;
void BFS_dfs(int step,int x,int y) {
inq[S.x][S.y] = true;
if (x == T.x&&y == T.y) {
if (step>=0&&step < min_step) {
min_step = step; //更新最小步数
}
return;
}
//if (test(x, y) == false) return;
for (int i = 0;i < 4;i++) {
int newx = x + X[i];
int newy = y + Y[i];
if (test (newx,newy)) {
inq[newx][newy] = true;
BFS_dfs(step + 1, newx, newy);
}
}
return;
}
int main() {
scanf_s("%d%d", &n, &m);
for (int i = 0;i < n;i++) {
getchar();
for (int j = 0;j < m;j++) {
maze[i][j] = getchar();
}
maze[i][m + 1] = '\0';
}
scanf_s("%d%d%d%d", &S.x, &S.y, &T.x, &T.y);
BFS_dfs(0, S.x, S.y);
//S.step = 0;
//printf("%d", BFS();
printf("%d", min_step);
return 0;
}