简单的迷宫问题(DFS+回溯)

输入一个n×n的迷宫,规定左上角为起点,右下角为终点,寻找一条路径

输入:n,表示迷宫的尺寸

随后是n×n的矩阵,0表示迷宫的道路,1表示墙壁

#include<bits/stdc++.h>
using namespace std;
const int dirx[4]={ 1, 0, 0,-1};
const int diry[4]={ 0, 1,-1, 0};        //定义四个方向,用于进行移动 
int maze[102][102];  			//存储迷宫 
int flag[102][102]; 			//用于记录迷宫中每个点是否被访问过 
int size;                               //迷宫的尺寸 
int pathfind=0; 			//用于标记是否找到正确路径 
void dfs(int x,int y){ 			//0表示可走路径,1表示墙壁,输出中的6表示正确路径 
	for(int i=0;i<4;i++){        
		int tempx = x + dirx[i];
		int tempy = y + diry[i];//四个方向分别试探 
		if(tempx>=0 && tempx<size && tempy>=0 && tempy<size && maze[tempx][tempy]==0 && flag[tempx][tempy]==0){ //检测该位置是否合法(非墙壁、未访问过、在迷宫范围内) 
			if(tempx==size-1 && tempy==size-1 || pathfind==1){ //判断是否到达出口,已经是否已经找到正确路径 
				pathfind=1;
				return;
			}
			flag[tempx][tempy]=1;			        //标记已访问过的点 
			dfs(tempx,tempy);				//递归调用dfs函数,从当前点开始搜索 
			if(pathfind==1){				//若已找到正确路径,则将正确路径以6覆盖,便于输出 
				maze[size-1][size-1]=6;
				maze[tempx][tempy]=6;
				maze[0][0]=6; 
			}
			flag[tempx][tempy]=0;			        //回溯标记,在进入死胡同时可回头 
		}
	}
	return;
}
int main(){
	memset(maze,0,sizeof(maze));
	memset(flag,0,sizeof(flag));
	cin>>size;
	flag[0][0]=1;
	for(int i=0;i<size;i++){			//输入迷宫信息(0表示道路,1表示墙壁) 
		for(int j=0;j<size;j++){
			cin>>maze[i][j];
		}
	}
	dfs(0,0);							//从起点开始搜索 
	cout<<endl;
	for(int i=0;i<size;i++){
		for(int j=0;j<size;j++){
			cout<<maze[i][j]<<" ";
		}
		cout<<endl;
	}
	return 0;
} 
几组测试数据:
5
0 1 1 1 1
0 0 0 0 1
1 1 1 0 1
0 0 0 0 1
0 1 1 0 0

6
0 0 1 1 0 0
1 0 1 0 0 1
1 0 0 0 1 1
0 0 1 0 1 1
1 0 1 0 0 0
1 1 1 1 1 0

因为是帮人答疑时匆忙写出的代码,同时也是第一次真正自己写出迷宫DFS代码,因此细节处理尚存在很大问题,还需努力学习

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/linyiduo123/article/details/79619954
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞