您的位置:首页 > 编程语言 > C语言/C++

第四届蓝桥杯C++A组 振兴中华

2018-03-27 20:56 417 查看
标题:振兴中华小明参加了学校的趣味运动会,其中的一个项目是:跳格子。地上画着一些格子,每个格子里写一个字,如下所示:(也可参见p1.jpg)从我做起振
我做起振兴
做起振兴中
起振兴中华

比赛时,先站在左上角的写着“从”字的格子里,可以横向或纵向跳到相邻的格子里,但不能跳到对角的格子或其它位置。一直要跳到“华”字结束。要求跳过的路线刚好构成“从我做起振兴中华”这句话。请你帮助小明算一算他一共有多少种可能的跳跃路线呢?答案是一个整数,请通过浏览器直接提交该数字。
注意:不要提交解答过程,或其它辅助说明类的内容。

思路:dfs,因为只能向右或向下走,所以我们可以用(4,5)作为终点,也可以用步数作为终点。
答案:35
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<set>
using namespace std;

int x[2] = { 1,0 }, y[2] = { 0,1 };
int vis[4][5] = { 0 };
int ans = 0;

void dfs(int a,int b)
{
if (a > 4 || b > 5)
return;
if (a == 4 && b == 5)
{
ans++;
return;
}
for (int i = 0; i < 2; i++)
{
int c = a + x[i];
int d = b + y[i];
if (c >= 1 && c <= 4 && d >= 1 && d <= 5)
{
if (!vis[c - 1][d - 1])
vis[c - 1][d - 1] = 1;
dfs(c, d);
vis[c - 1][d - 1] = 0;
}
}
}
int main()
{
vis[0][0] = 1;
dfs(1, 1);
cout << ans << endl;
return 0;
}
PS:用步数作为dfs终点的出处:https://blog.csdn.net/u010625743/article/details/44630055
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<set>
using namespace std;

int a[4][5];
int sum;
void dfs(int row, int col, int index)
{
if (a[row][col] == index && index == 7)
sum++;
else
{
if (row + 1<4)
dfs(row + 1, col, index + 1);
if (col + 1<5)
dfs(row, col + 1, index + 1);
}
}
int main()
{
int row, col;
for (row = 0; row<4; row++)
for (col = 0; col<5; col++)
a[row][col] = row + col;

dfs(0, 0, 0);
cout<<sum<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dfs