深度搜索的变形

21 篇文章 0 订阅
9 篇文章 0 订阅

题目:


题目分析,题目给人的感觉就是深度搜索,找出所有的路径,但是条件(6)使这个标记已找到的路径与标准的深搜不一样,只需要标记当前路径的即可:

#include <Stack>
#include <iostream>
int main() {
	/* Enter your code here. Read input from STDIN. Print output to STDOUT */

	int n;
	int m;
	int num;
	int targetPos;
	int firstPos;
	std::cout << "Input :" << std::endl;
	std::cin >> n >> m;
	for(int i = 0; i < n*m ; i++)
	{
		int tt;
		std::cin >> tt;
		if (tt == 1)
			firstPos = i;
		if (tt == 2)
			targetPos = i;
	}
	std::cin >> num;

	int allNum = 0;
	

	int vv[1000] = {0};
	std::stack<std::pair<int, int>> nodestack;
	std::stack<std::pair<int, int>> curPath;
	nodestack.push(std::make_pair(firstPos, 1));

	bool arreve =false;

	while (!nodestack.empty())
	{
		int node = nodestack.top().first;
		int depth = nodestack.top().second;
		int cc = node/m;
		int dd = node%m;

		nodestack.pop();
		// ----- > t
		if (depth > num)
			continue;;

		// clear the same depth 
		while(!curPath.empty())
		{
			if(depth > curPath.top().second)
				break;
			vv[curPath.top().first] = 0;

			if (curPath.top().first == targetPos) // clear the arrave
				arreve = false;
			curPath.pop();
		}

	

		// - neighbour -----------
		int ll = std::max(cc-1, 0);
		int rr = std::min(cc+2, n);
		int uu = std::max(dd-1, 0);
		int d  = std::min(dd+2, m);
		for (int ii=ll; ii< rr;ii++)
		{
			for(int jj=uu; jj<d;jj++)
			{
				if (vv[ii*m+jj] != 1)
				{
					nodestack.push(std::make_pair(ii*m+jj, depth+1));
				}
			}
		}

		// 
		if (node == targetPos)
			arreve = true;

		if (arreve && depth == num)
			allNum += 1;




		// add the current path and label
		curPath.push(std::make_pair(node, depth));
		vv[node] = 1;
	

	}

	std::cout << "OutPut :" << std::endl;
	std::cout << allNum << std::endl;
	return 0;    
}

运行结果:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值