一、題目
小明參加了學校的趣味運動會,其中的一個項目是:跳格子。
地上畫着一些格子,每個格子裏寫一個字,如下所示:(也可參見p1.jpg)
比賽時,先站在左上角的寫着“從”字的格子裏,可以橫向或縱向跳到相鄰的格子裏,但不能跳到對角的格子或其它位置。一直要跳到“華”字結束。
要求跳過的路線剛好構成“從我做起振興中華”這句話。請你幫助小明算一算他一共有多少種可能的跳躍路線呢?
答案是一個整數,請通過瀏覽器直接提交該數字。
注意:不要提交解答過程,或其它輔助說明類的內容。
二、思路
其實說實在的,用8個不同數字代表“從我做起振興中華”然後手寫強算也是可以的hhhhh,就是普通的組合問題。
但是從左上角開始計算,只有兩個移動方向,所以這裏選擇使用dfs來計算。
可以設定(1,1)爲起點,(4,5)作爲終點,或者可以用步數(8)作爲終點。
三、題解
#include <iostream> using namespace std; int right_direction[2]={1,0};//向右移動 int down_direction[2]={0,1};//向下移動 int visited[4][5]={0};//默認沒有訪問過 int ans=0;//記錄路線數量 void dfs(int row,int column) { if(row>4 || column>5 ) //越界情況 { return ; } if(row==4 && column==5) { ans++; return; } for (int i=0;i<2;i++)//移動 { int right_forward = row + right_direction[i]; int down_forward = column + down_direction[i]; if(right_forward >= 1 && right_forward <= 4 && down_forward >= 1 && down_forward <= 5 ) { if(!visited[right_forward-1][down_forward-1]) { visited[right_forward-1][down_forward-1]=1; } dfs(right_forward,down_forward); visited[right_forward-1][down_forward-1]=0; } } } int main() { visited[0][0]=1; dfs(1,1); cout << ans << endl; return 0; }
四、結果
35
Process finished with exit code 0