洛谷1605深搜

LG1605

C++

题源入口

#include<iostream>
using namespace std;
#define N 10000
int map[N][N]= {0},book[N][N]= {0},n,m,bar;
int startx,starty,endx,endy,ans=0;
int next[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};
void dfs(int x,int y) {
	int i,tx,ty;
	if(x==endx&&y==endy) {
		ans++;
		return;
	} else {
		for(i=0; i<=3; i++) {
			tx=x+next[i][0];
			ty=y+next[i][1];
			if(tx<1||ty<1||tx>n||ty>m)
				continue;
			else if(map[tx][ty]==0&&book[tx][ty]==0) {
				book[tx][ty]=1;
				dfs(tx,ty);
				book[tx][ty]=0;
			}
		}
	}
	return;
}
int main() {
	int a,b;
	cin>>n>>m>>bar;
	cin>>startx>>starty>>endx>>endy;
	while(bar--) {
		cin>>a>>b;
		map[a][b]=2;
	}
	map[startx][starty]=1;
	dfs(startx,starty);
	cout<<ans;
	return 0;
}

Tips

1、在使用深度优先搜索的时候,要先把起点先在map中标记,防止后面重复走。
      map[startx][starty]=1;
2、在dfs中重新设置下一步的tx,ty,而不能直接在原来的x,y上进行更新。
3、变量i不可以设置在全局变量中,之前一次因为这个原因耽搁了半天,每一次的递归中i应该是独立的。
4、在写代码的时候注意地图n,m表示的是行还是列(细节决定成败)。
5、第一个return;用于调用的返回,若缺失,导致程序无法停止报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值