1:坑点:
DFS想法:一条路走到黑,不行就返回。
但是,题目只需要我们输出一条路径,所以我们的vis数组不需要取消标记(我就是被这个坑了)
2:路径存储
up采用stack来储存,这样子每次回溯只需要pop一下,很方便,有木有~
if(x==n&&y==m){//结束
stack<node>s;
while(!st.empty()){
s.push(st.top());
st.pop();
}
while(!s.empty()){
cout<<s.top().x<<" "<<s.top().y<<"\n";
s.pop();
}
exit(0);
}
3:结束优化
我们找到一条后就可以输出答案并结束啦,我们可以采用exit(0),他可以让程序直接停止,这样子我们不用让dfs一路return啦~
4:ACcdoe:
#include<bits/stdc++.h>
using namespace std;
const int N=115;
#define int long long
int n,m,idx[]={0,0,1,-1},idy[]={1,-1,0,0};
bool vis[N][N];
char mp[N][N];
struct node{
int x,y;
};
stack<node>st;
void dfs(int x,int y){
if(x==n&&y==m){//结束
stack<node>s;
while(!st.empty()){
s.push(st.top());
st.pop();
}
while(!s.empty()){
cout<<s.top().x<<" "<<s.top().y<<"\n";
s.pop();
}
exit(0);
}
for(int i=0;i<4;i++){
int xx=x+idx[i];
int yy=y+idy[i];
if(xx<1||xx>n||yy<1||yy>m||vis[xx][yy]||mp[xx][yy]=='*')
continue;
vis[xx][yy]=true;
st.push({xx,yy});
dfs(xx,yy);
//vis[xx][yy]=false;
st.pop();
}
}
void solve() {
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>mp[i][j];
st.push({1,1});
dfs(1,1);
}
signed main() {
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int tt=1;
//cin>>tt;
while(tt--)
solve();
return 0;
}
over~