首先解决一下需要用到的知识:
1.BFS:常用来解决最短路径以及涉及最小、最大等问题,比DFS更优。
DFS:常用来判断能否找到出口、解。
【ps:如果 路径唯一,DFS来解决最短路径问题也是可以的】
2.vector<vector<int>>v(n,vector<int>(m,0)):
v中包含n个vector<int>类型数据,vector<int>(m,0)表示包含m个0。
3.vector<pair<int,int>>v(a,b):
只想存储pair对,不需要对其排序,可以将pair对插入vector即可。
for(auto it:v) cout<< it.first<<it.second 【也可利用迭代器访问元素】
4.main()函数里面定义的变量是局部变量,只不过它的生命周期与全局变量一样长
5.边界优先判断
代码:别人的,因为自己还没学到回溯,先背下来了,因为思路还是很清晰的~
#include<iostream>
#include<vector>
using namespace std;
vector<pair<int,int>> ans;//最终路径
vector<pair<int,int>> temp;//暂存路径
int row,col;//迷宫的行数和列数
bool flag=false;//用于递归结束判断
void dfs(vector<vector<int>> &dp,int a,int b){
temp.push_back({a,b});
dp[a][b] = 1;//将当前位置的0改为1,表示当前位置已经访问过了,不可重复访问
if(a == row - 1 && b == col - 1){//已经走到了右下角
ans = temp;//保存最终路径
flag = true;//结束循环
return;
}
if(a+1 < row && dp[a+1][b] == 0){
dfs(dp,a+1,b);//向下走
if(flag) return;
}
if(b+1 < col && dp[a][b+1] == 0){
dfs(dp,a,b+1);//向右走
if(flag) return;
}
if(a-1 >= 0 && dp[a-1][b] == 0){
dfs(dp,a-1,b);//向上走
if(flag) return;
}
if(b-1 >= 0 && dp[a][b-1] == 0){
dfs(dp,a,b-1);//向左走
if(flag) return;
}
temp.pop_back();//回溯
dp[a][b] = 0;//恢复当前位置为0
}
int main(){
while(cin >> row >> col){//输入迷宫的大小
vector<vector<int>> dp(row,vector<int>(col,0));
for(int i = 0;i < row;i++){//输入迷宫
for(int j = 0;j < col;j++){
cin >> dp[i][j];
}
}
dfs(dp,0,0);
for(auto it:ans){//输出最终路径
cout << '(' << it.first << ',' << it.second << ')' << endl;
}
//清空
ans.clear();
temp.clear();
}
return 0;
}