回溯法原理
可以参考我的另一篇博客。
回溯法之迷宫问题
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;
}