P6207 [USACO06OCT] Cows on Skates G(dfs之回溯不用取消vis标记)

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~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值