这个题目也是一个典型的BFS题目,也可以用递归求解 . . .
题目: 一个二维矩阵从坐标(1,1)出发,到终点(n,m),问一共有几条路线可以通过?
注意题目的两点要求:
- 矩阵下标为双偶数的禁止路过,比如(2,2)、(4,4)等点 . . .
- 只能向右或者向下路行 . . .
例如下面的图所示:
这个有三行四列的矩阵,从(1,1)到达(3,4)这个点有两条路径 . . .
…
递归 求解
#include <iostream>
using namespace std;
int n, m; // 矩阵的行列大小
int count = 0; // 满足题意的几种途径
void useRecursion(int x, int y)
{
if(x % 2 == 0 && y % 2 == 0) return; // 判断是否是双偶数方格,禁止通行
if(x == n && y == m) ++count; // 判断是否到达终止了
if(x+1<=n) // 向下通行
useRecursion(x + 1, y);
if(y+1<=m) // 向右通过
useRecursion(x, y + 1);
}
int main()
{
cin >> n >> m;
useRecursion(1, 1); // 从(1,1)点开始递归探索
cout << count << endl;
return 0;
}
.
BFS 求解
#include <iostream>
#include <queue>
using namespace std;
int n, m; // 数组大小
int count = 0; // 满足条件的个数
// 两个方向
int direction[2][2] = { {0, 1}, {1, 0} };
// 表示矩阵中的某个点
struct Pos { int x; int y; };
void bfs()
{
queue<Pos> que;
que.push({1, 1}); // 第一个点入队
while(!que.empty()){
Pos pos = que.front();
que.pop(); // 获得第一个点后,记得出队
for(int i = 0; i < 2; ++i){
int cx = pos.x + direction[i][0]; // 获取下一个方向
int cy = pos.y + direction[i][1];
if(cx > n || cy > m) continue; // 数组越界
// 偶数点禁止通行
if(cx % 2 == 0 && cy % 2 == 0) continue;
// 找到终止了
if(cx == n && cy == m) ++count;
// 当前访问的这个点入队了
que.push({cx, cy});
}
}
}
int main()
{
cin >> n >> m;
bfs();
cout << count << endl;
return 0;
}
代码仅供参考,如有错误,多多包含 ^ _ ^