it面试题-老鼠走迷宫变形体

本文介绍了一道面试题,涉及二维坐标图中老鼠从(0,0)到(4,4)的路径寻找,需避开(2,1)节点且不重复经过其他点。采用回溯法进行算法设计,利用栈实现。提供了C++代码实现,但缺失头文件。" 104694005,9269741,ElasticSearch 入门指南:原理、操作与实践,"['ElasticSearch', 'Java', 'Kibana', '全文检索', '数据检索']

个人简介:it男,算法爱好者学习者,男,目前在大公司实习,2015应届生

题目:给出二维坐标图,其中一个正方形区域,一共有从(0,0)到(4,4)25个节点,但是(2,1)节点是不能通过的,问有没有一条路径从(0,0)出发,然后到达(4,4),不经过(2,1),其他的点必须经过还不能重复经过,每次只可以往上下左右四个方向走,不可以斜着走,不可以跳着走。

算法:回溯法遍历,用栈实现,老鼠走迷宫的变形题

代码:C++ 实现(代码缺少头文件)

#include <iostream>
#include <stack>
using namespace std ;


int main()
{
	int const size = 5;
	int table[5][5];
	for(int i=0;i<size;i++)
	{
		for(int j=0;j<size;j++)
		{
			table[i][j] = 0;
		}
	}
	table[2][1] = -1 ;
	stack<pair<int,int>> load ;
	stack<int> dir;
	load.push(std::make_pair(0,0));
	table[0][0] = 1;
	int nowdir = 0;
	while(! load.empty())
	{
		pair<int,int> node = load.top();
		if( node.second < size-1 && table[node.first][node.second+1] == 0 && nowdir < 1 )
		{
			table[node.first][node.second+1] = 1;
			load.push(std::make_pair(node.first,node.second+1));
			dir.push(1);
		}
		else if(node.first-1 >=0 && table[node.first-1][node.second] == 0 && nowdir < 2 )
		{
			table[node.first-1][node.second] = 1;
			load.push(std::make_pair(node.first-1,node.second));
			dir.push(2);
		}
		else if(node.second-1 >=0 && table[node.first][node.second-1] == 0  && nowdir < 3)
		{
			table[node.first][node.second-1] = 1;
			load.push(std::make_pair(node.first,node.second-1));
			dir.push(3);
		}
		else if(node.first < size-1 && table[node.first+1][node.second] == 0 && nowdir < 4 )
		{
			table[node.first+1][node.second] = 1;
			load.push(std::make_pair(node.first+1,node.second));
			dir.push(4);
		}
		else if(node.first == size-1 && node.second == size-1 && load.size() == 24)
		{
			cout<<"okSS";
			break;
		}
		else {
			table[node.first][node.second] = 0;
			load.pop();
			if(! dir.empty()){
				nowdir = dir.top();
				dir.pop();
			}
			else
			{
				cout<<"no path"<<endl;
			}
		}
	}

	system("pause");
	return 0;
}

答案是没有这么一条路径满足要求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值