迷宫 DFS 算法

本文介绍了一个使用深度优先搜索(DFS)算法解决迷宫最短路径问题的C++程序实现。通过定义地图和访问状态数组,该程序能够从起点出发寻找到达终点的最短步数。代码中详细展示了如何递归地探索四个方向,并更新最小步数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>

using namespace std;

#define _CRT_SECURE_NO_WARNINGS

int map[51][51],vis[51][51];

int N,M;

int sx, sy, ex, ey;

int a[] = { 1, -1, 0, 0 };

int b[] = { 0, 0, 1, -1 };

int min = 99999999;

void dfs(int x, int y, int step){

 int tx, ty;  

if (x==ex&&y==ey){   

  if (step < min)    min = step;   

  return;  

}  

for (int k = 0; k < 4; k++){  

 tx = x + a[k];   ty = y + b[k];  

 if (tx<1 || tx>N || ty<1 || ty>M) continue;   

if (map[tx][ty] == 1) continue;  

 if (vis[tx][ty] == 1) continue;   

vis[tx][ty] = 1;   

dfs(tx,ty,step+1);   

vis[tx][ty] == 0;  

}  

}

int main(){  

freopen("input.txt","r",stdin);

 int T;  

cin >> T;  

for (int t = 1; t <= T; t++){   

cin >> N >> M;   

for (int i = 1; i <= N; i++){   

 for (int j = 1; j <= M; j++){     

cin >> map[i][j];    

}  

 }   

cin >> sx >> sy >> ex >> ey;   

vis[sx][sy] = 1;  

 dfs(sx,sy,0);   

cout << min;  

}    

while (1);  

return 0;

}

转载于:https://www.cnblogs.com/wujixing/p/6306849.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值