洛谷P1238 走迷宫

时间:2023-11-11 11:45:32

洛谷1238 走迷宫

题目描述

有一个m*n格的迷宫(表示有m行、n列),其中有可走的也有不可走的,如果用1表示可以走,0表示不可以走,文件读入这m*n个数据和起始点、结束点(起始点和结束点都是用两个数据来描述的,分别表示这个点的行号和列号)。现在要你编程找出所有可行的道路,要求所走的路中没有重复的点,走时只能是上下左右四个方向。如果一条路都不可行,则输出相应信息(用-l表示无路)。

输入输出格式

输入格式:

第一行是两个数m,n(1<m,n<15),接下来是m行n列由1和0组成的数据,最后两行是起始点和结束点。

输出格式:

所有可行的路径,描述一个点时用(x,y)的形式,除开始点外,其他的都要用“一>”表示方向。
    如果没有一条可行的路则输出-1。

输入输出样例

输入样例#1:

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

输出样例#1:

(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)->(

【思路】

回溯法。

因为题目要求输出不同路径,所以我们采用回溯法搜索路径并输出。

需要注意的有:

1、   起始点==终点则输出-1

2、   一定不要忘记标记起始点。

【代码】

 #include<iostream>
#include<cstring>
#include<queue>
#include<vector>
using namespace std; const int maxn = ;
const int dx[]={,-,,};
const int dy[]={-,,,}; int G[maxn][maxn];
int vis[maxn][maxn];
int A[maxn*maxn][];
int n,m,e_x,e_y;
bool f=false; inline bool inside(int x,int y) {
return x>= && x<=n && y>= && y<=m && G[x][y];
} void dfs(int x,int y,int d)
{
if(x==e_x && y==e_y)
{
for(int i=;i<d-;i++)
cout<<"("<<A[i][]<<","<<A[i][]<<")->";
cout<<"("<<e_x<<","<<e_y<<")"<<endl;
f=true;
return ;
}
for(int i=;i<;i++)
{
int xx=x+dx[i],yy=y+dy[i];
if(inside(xx,yy) && !vis[xx][yy])
{
vis[xx][yy]=;
A[d][]=xx; A[d][]=yy;
dfs(xx,yy,d+);
vis[xx][yy]=;
}
}
} int main() {
ios::sync_with_stdio(false);
cin>>n>>m;
for(int i=;i<=n;i++)
for(int j=;j<=m;j++)
cin>>G[i][j];
int f_x,f_y;
cin>>f_x>>f_y>>e_x>>e_y;
if(f_x==e_x && f_y==e_y) {
cout<<-;
return ;
} A[][]=f_x, A[][]=f_y;
vis[f_x][f_y]=;
dfs(f_x,f_y,); if(!f) cout<<-;
return ;
}