サー、最近私は再帰スキルを向上させていますが、「コーディングスキルのクラッキング」という本の再帰問題の1つで立ち往生しています。問題番号8.2
問題の説明は次のとおりです。ロボットがN*Nグリッドの上部の隅に座っていると想像してください。ロボットは、右と下の2つの方向にしか移動できません。ロボットにはいくつの可能な経路がありますか?
私はたくさん試しましたが、それは私に単一のパスしか示していません。私のコードは(本の解決策から助けを借りて)
#include<iostream>
#include<vector>
using namespace std;
struct point {
int x;
int y;
};
vector<struct point *> v_point;
int findPath(int x, int y) {
struct point *p = new point;
p->x = x;
p->y = y;
v_point.push_back(p);
if(x == 0 && y == 0) {
cout << "\n\t" << x << " " << y;
return true;
}
int success = 0;
if( x >= 1 ) {
cout << "\n success = " << success << " x = " << x << " " << " y = " << y;
success = findPath(x-1, y);
cout << "\n success = " << success << " x = " << x << " " << " y = " << y;
}
if(!success && y >= 1) {
cout << "\n\t success = " << success << " x = " << x << " " << " y = " << y;
success = findPath(x, y-1);
cout << "\n\t success = " << success << " x = " << x << " " << " y = " << y;
}
if(!success){
cout << "\n\t\t success = " << success << " x = " << x << " " << " y = " << y;
v_point.pop_back();
cout << "\n\t\t success = " << success << " x = " << x << " " << " y = " << y;
}
return success;
}
main() {
cout << endl << findPath(3, 3);
return 0;
}
printfステートメントを配置して、どこが間違っているかを確認しましたが、間違いは見つかりませんでした。私を助けてください。
私はあなたの指示によって与えられたコードを書きました。しかし、すべてのパスを印刷したい場合、それは望ましくない答えを与えます。
int findPath(int x, int y) {
if(x == 0 && y == 0) { cout << endl; return 1; }
int path = 0;
if(x > 0) { cout << "d -> ";path = path + findPath(x-1, y); } // d = down
if(y > 0) { cout << "r -> ";path = path + findPath(x, y-1); } // r = right
return path;
}
3 * 3のグリッドの場合(findPaths(2、2)):-
d -> d ->r -> r ->
r -> d -> r ->
r -> d->
r -> d -> d -> r ->
r -> d ->
r -> d -> d ->