18714 迷宫问题
PS:scanf()输入是用指针操作!!记得加‘&’
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
int n,m;//迷宫范围
//定义函数判断点是否在迷宫中
bool InAera(int &row,int &col){ //要加引用符
return row >= 0 && col >= 0 && row < n && col < m; //都在迷宫范围内,返回true
}
//定义函数深搜能否走出迷宫
bool dfs(vector<string> &MG_map,int row,int col){
//出口
if(!InAera(row,col) || MG_map[row][col] == '1') return false;//点不在迷宫内,或者点不可通行(迷宫走不出来)
if(row == n - 1 && col ==m - 1) return true;//入口即出口
//深搜
//走过的点且不是出口的置为‘1’
MG_map[row][col] = '1';
//往上下左右走(递归)
bool left = dfs(MG_map,row,col - 1);//左
bool right = dfs(MG_map,row,col + 1);//右
bool up = dfs(MG_map,row - 1,col);//上
bool down = dfs(MG_map,row + 1,col);//下
//上下左右任意能走即能通
return left || right || up || down;
}
int main()
{
//ios::sync_with_stdio(false);
cin >> n >> m;
//输入迷宫地图
vector<string> MG_map(n);//构建一个n行的字符串向量(相当于二维)
for(int i = 0;i < n;i++){ //每行
MG_map[i].resize(m);//设置第n行的长度(列)为m
/* string x;
//cin >> x;
//MG_map.push_back(x); //迷宫某点坐标(一行的列坐标)*/
//直接输入坐标(不用push_bcak()
for(int j = 0;j < m;j++){
cin >> MG_map[i][j];
}
}
//走迷宫
if(dfs(MG_map,0,0)){ //从(0,0)开始走,如果能走到出口,返回true
cout << "yes" << endl;
}
else cout << "no" << endl; //失败
return 0;
}
相关迷宫问题:(进阶)OJ笔记 18720 迷宫问题 (最短路径)