原文链接:https://www.luogu.com.cn/problem/P1238
AC代码:
#include<iostream>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
int n,m,flag=-1;
int dir0[4]={0,-1,0,1};
int dir1[4]={-1,0,1,0};
int mapp[20][20];
int sx,sy,ex,ey;
int visit[20][20];
typedef struct node{
int x,y;
}node;
node nod,nodd;
vector<node> vec;
void dfs(int x,int y){
int i,j;
if(x==ex&&y==ey){
flag=0;
for(i=0;i<vec.size();i++){
nod=vec[i];
cout<<"("<<nod.x+1<<","<<nod.y+1<<")";
if(i!=vec.size()-1){
cout<<"->";
}
}
cout<<endl;
return ;
}
for(i=0;i<4;i++){
nodd.x=x+dir0[i];nodd.y=y+dir1[i];
if(visit[x+dir0[i]][y+dir1[i]]==1) continue;
if(mapp[x+dir0[i]][y+dir1[i]]==0) continue;
visit[x+dir0[i]][y+dir1[i]]=1;
vec.push_back(nodd);
dfs(x+dir0[i],y+dir1[i]);
vec.pop_back();
visit[x+dir0[i]][y+dir1[i]]=0;
}
}
int main(){
int i,j;
cin>>n>>m;
memset(mapp,0,sizeof(mapp));
memset(visit,0,sizeof(visit));
for(i=0;i<n;i++){
for(j=0;j<m;j++){
cin>>mapp[i][j];
}
}
cin>>sx>>sy>>ex>>ey;
sx--;sy--;ex--;ey--;
nod.x=sx;nod.y=sy;
vec.push_back(nod);
visit[sx][sy]=1;
dfs(sx,sy);
if(flag==-1) cout<<flag<<endl;
return 0;
}