回溯法之迷宫问题(华为笔试题)

回溯法原理

可以参考我的另一篇博客

回溯法之迷宫问题

2020/8/12日的华为笔试出了一道笔试迷宫问题的改版,题目大致的意思如下:
有一条刚贴地砖的路,强迫症小明走路每次走的步长一样,并且只走贴了地砖的地方,如果用1代表贴了地砖,用0代表没有地砖,问小明能否从左上角出发走到终点右下角。
例题:
输入

2
3 5
1 0 1 0 0
0 0 0 1 0
0 0 1 0 1

输出

true

其中2是步长,即小明一次走两步,3和5分别代表行数和列数。下面3行5列是代表有地砖和没有地砖。小明只要按照(0,0),(0,2),(2,2),(2,4)的路线就可以走到终点。

代码

这里的代码不仅能确定小明能否走到终点,而且能计算一共有几种走的方式。具体看下面的代码。

//经典的回溯法
//华为面试:走迷宫
#include <iostream>
using namespace std;
int path[3][5] = {	{1,1,1,1,1},
					{0,0,0,0,1},
					{0,0,0,0,1} };
int step = 1;
int rowOut = 3;
int colOut = 5;
int way = 0;

bool feasible(int row, int col)
{
	if (row < rowOut && col < colOut && row >= 0 && col >= 0 && path[row][col] == 1)
		return true;
	else
		return false;
}

void getPath(int row, int col)
{
	if (row == rowOut-1 && col == colOut-1)//到达终点
	{
		way++;
		return;
	}
	else
	{
		if (feasible(row, col + step))//是否可行
		{
			col += step;
			getPath(row, col);
			col -= step;//回溯
		}	
		if (feasible(row + step, col))
		{
			row += step;
			getPath(row, col);
			row -= step;//回溯
		}
	}
}

int main()
{
	cin >> step;
	cin >> rowOut >> colOut;
	for (int i = 0; i < rowOut; i++)
	{
		for (int j = 0; j < colOut; j++)
		{
			cin >> path[i][j];
		}
	}
	getPath(0, 0);
	if (way>0)
		cout << "OK! way=" << way << endl;
	else
		cout << "false!" << endl;
	system("pause");
	return 0;
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值