解题思路:用dfs+回溯即可解决问题,注意回溯的修改还有就是顺序为左上右下,还有没有答案时输出-1.
#include<bits/stdc++.h>
using namespace std;
using gg = long long;
int n,m;
int visited[20][20];//访问数组
int arr[20][20];
int end_x,end_y;
vector<vector<pair<int,int> > > res;
void dfs(int x,int y,vector<pair<int,int> > temp)
{
if(x<1||x>n||y<1||y>m||arr[x][y]==0||visited[x][y])
{
return;
}
else if(x==end_x&&y==end_y)
{
temp.push_back(make_pair(x,y));
res.push_back(temp);
}
else
{
//if(arr[x][y]==1){cout<<x<<" "<<y<<" "<<endl;}
temp.push_back(make_pair(x,y));
visited[x][y]=1;
dfs(x,y-1,temp);
dfs(x-1,y,temp);
dfs(x,y+1,temp);
dfs(x+1,y,temp);//左上右下
visited[x][y]=0;
temp.pop_back();
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>arr[i][j];
}
}
int start_x,start_y;
cin>>start_x>>start_y;
cin>>end_x>>end_y;
vector<pair<int,int> > temp;
dfs(start_x,start_y,temp);
gg size = res.size();
if(size==0)
{
cout<<-1<<"\n";
}
//cout<<size<<endl;
for(int i=0;i<size;i++)
{
gg length = res[i].size();
for(int j=0;j<length-1;j++)
{
cout<<"("<<res[i][j].first<<","<<res[i][j].second<<")"<<"->";
}
cout<<"("<<end_x<<","<<end_y<<")"<<"\n";
}
return 0;
}