标题: 振兴中华
小明参加了学校的趣味运动会,其中的一个项目是:跳格子。
地上画着一些格子,每个格子里写一个字,如下所示:(也可参见p1.jpg)
从我做起振
我做起振兴
做起振兴中
起振兴中华
比赛时,先站在左上角的写着“从”字的格子里,可以横向或纵向跳到相邻的格子里,但不能跳到对角的格子或其它位置。一直要跳到“华”字结束。
要求跳过的路线刚好构成“从我做起振兴中华”这句话。
请你帮助小明算一算他一共有多少种可能的跳跃路线呢?
答案是一个整数,请通过浏览器直接提交该数字。
注意:不要提交解答过程,或其它辅助说明类的内容。
分析:把格子丢到字符数组里面就好了,然后对图DFS一下,验证每条到达终点的路径中所含的字符是否符合要求。这里用结构体储存每个节点会很方便。
代码:
#include<iostream>
using namespace std;
char grid[4][5] =
{
'从', '我', '做', '起', '振',
'我', '做', '起', '振', '兴',
'做', '起', '振', '兴', '中',
'起', '振', '兴', '中', '华'
};
char word[8] = {'从', '我', '做', '起', '振', '兴', '中', '华'};
struct Node{
int x;
int y;
char word;
}node[8];
int visit[4][5] = {0};
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int ans = 0;
int index = 0;
void check()
{
for(int i = 0; i < 8; i++)
if(node[i].word != word[i])
return;
ans++;
}
void dfs(int x, int y)
{
if(x == 3 && y == 4 && index == 8)
{
check();
return;
}
if(x < 0 || x >= 4 || y < 0 || y >= 5 || index >= 8)
return;
for(int i = 0; i < 4; i++)
{
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if(visit[nx][ny] == 0 && nx >= 0 && nx <= 3 && ny >= 0 && ny <= 4)
{
visit[nx][ny] = 1;
node[index++] = {nx, ny, grid[nx][ny]};
dfs(nx, ny);
visit[nx][ny] = 0;
index--;
}
}
}
int main()
{
node[0] = {0, 0, '从'};
index = 1;
dfs(0, 0);
cout << ans << endl;
return 0;
}