题目描述 Description
现在有一个m*n的由数字0和1组成的迷宫,其中1代表能走,0代表不能走,现在给你起点和终点,你需要找出所有的通过方式,并且通过过程中不能有重复的点,只能走上下左右四个方向。
优先顺序:左上右下
输入描述 Input Description
第一行是两个数m,n(1<m,n<15),接下来是m行n列由1和0组成的数据,最后两行是起始点和结束点。
输出描述 Output Description
所有可行的路径,描述一个点时用(x,y)的形式,除开始点外,其他的都要用“一>”表示方向。
如果没有一条可行的路则输出-1。
样例输入 Sample Input
5 6 1 0 0 1 0 1 1 1 1 1 1 1 0 0 1 1 1 0 1 1 1 1 1 0 1 1 1 0 1 1 1 1 5 6
样例输出 Sample Output
(1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(2,5)->(3,5)->(3,4)->(3,3)->(4,3)->(4,4)->(4,5)->(5,5)->(5,6) (1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(2,5)->(3,5)->(3,4)->(4,4)->(4,5)->(5,5)->(5,6) (1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(2,5)->(3,5)->(4,5)->(5,5)->(5,6) (1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(3,4)->(3,3)->(4,3)->(4,4)->(4,5)->(5,5)->(5,6) (1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(3,4)->(3,5)->(4,5)->(5,5)->(5,6) (1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(3,4)->(4,4)->(4,5)->(5,5)->(5,6) (1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,4)->(2,4)->(2,5)->(3,5)->(4,5)->(5,5)->(5,6) (1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,4)->(3,5)->(4,5)->(5,5)->(5,6) (1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,4)->(4,4)->(4,5)->(5,5)->(5,6) (1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(4,3)->(4,4)->(3,4)->(2,4)->(2,5)->(3,5)->(4,5)->(5,5)->(5,6) (1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(4,3)->(4,4)->(3,4)->(3,5)->(4,5)->(5,5)->(5,6) (1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(4,3)->(4,4)->(4,5)->(5,5)->(5,6)
童鞋们,这道题目是酷丁编程J3后期的题目,如果不是J3的就尽量别看了
这道题目推荐用dfs(深搜)
用广搜很多童鞋都不大懂
深搜特别容易理解
#include<iostream>
using namespace std;
int m,n,a[20][20],sx,sy,ex,ey;
bool vis[20][20],g[20][20],flag;
int dir[4][2]={{0,-1},{-1,0},{0,1},{1,0}};
int f[400],l[400];
void dfs(int x,int y,int stay){
f[stay]=x;
l[stay]=y;
if(x==ex&&y==ey){
flag=true;
for(int i=1;i<stay;i++){
cout<<"("<<f[i]<<","<<l[i]<<")"<<"->";
}
cout<<"("<<f[stay]<<","<<l[stay]<<")"<<endl;
}
for(int i=0;i<4;i++){
int nx=x+dir[i][0],ny=y+dir[i][1];
if(nx>=1&&nx<=m&&ny>=1&&ny<=n&&a[nx][ny]==1&&!vis[nx][ny]){
vis[nx][ny]=true;
dfs(nx,ny,stay+1);
vis[nx][ny]=false;
}
}
}
int main(){
cin>>m>>n;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
cin>>a[i][j];
}
}
cin>>sx>>sy>>ex>>ey;
if(a[sx][sy]==0||a[ex][ey]==0){
cout<<-1;
return 0;
}
vis[sx][sy]=true;
dfs(sx,sy,1);
if(!flag){
cout<<"-1";
}
return 0;
}