题目描述:有一个n*m格的迷宫(表示有n行、m列),其中有可走的也有不可走的,如果用1表示可以走,0表示不可以走,文件读入这n*m个数据和起始点、结束点(起始点和结束点都是用两个数据来描述的,分别表示这个点的行号和列号)。现在要你编程找出所有可行的道路,要求所走的路中没有重复的点,走时只能是上下左右四个方向。如果一条路都不可行,则输出相应信息(用-l表示无路)。请统一用 左上右下的顺序拓展,也就是 (0,-1),(-1,0),(0,1),(1,0)
输入
第一行是两个数n,m( 1 < n , m < 15 ),接下来是m行n列由1和0组成的数据,最后两行是起始点和结束点。
输出
所有可行的路径,描述一个点时用(x,y)的形式,除开始点外,其他的都要用“->”表示方向。
如果没有一条可行的路则输出-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)->(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)
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <vector> #include <map> using namespace std; int n,m; const int maxn=20; int maxtri[maxn][maxn]; int flag[maxn][maxn]; vector<pair<int,int> > ans; pair<int ,int> begin_point,end_point; int X[4]={0,-1,0,1}; int Y[4]={-1,0,1,0}; int p_flag=0; void DFS(int x,int y) { flag[x][y]=1; ans.push_back(make_pair(x,y)); if(x==end_point.first&&y==end_point.second) { if(p_flag==0) p_flag=1; //ans.push_back(make_pair(x,y)); for(int i=0;i<ans.size();i++) { if(i>0) { printf("->"); } printf("(%d,%d)",ans[i].first,ans[i].second); } printf(" "); //ans.pop_back(); return ; } for(int i=0;i<4;i++) { int newx=x+X[i]; int newy=y+Y[i]; if(newx>=1&&newx<=n&&newy>=1&&newy<=m&&maxtri[newx][newy]==1&&flag[newx][newy]==0) { DFS(newx,newy); ans.pop_back(); flag[newx][newy]=0; } } } int main() { memset(flag,0,sizeof(flag)); scanf("%d %d",&n,&m); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { scanf("%d",&maxtri[i][j]); } } //画边界 for(int i=0;i<=n+1;i++) { for(int j=0;j<=m+1;j++) { if(i==0||j==0||i==n+1||j==m+1) { maxtri[i][j]=0; } } } scanf("%d %d",&begin_point.first,&begin_point.second); scanf("%d %d",&end_point.first,&end_point.second); DFS(begin_point.first,begin_point.second); if(p_flag==0) { printf("-1 "); } return 0; }