問題:不知道為什么第三次遞回函式沒有得到執行。只要求得到一種走法就可以了。
程式如下:
#include<iostream>
using namespace std;
#define MAX 20
class Point
{
public:
bool operator==(Point pp)
{
if (pp.Businessman == this->Businessman && pp.Slave == this->Slave)
return true;
else
return false;
}
int Businessman;
int Slave;
};
int step = 0;//船渡河次數
Point END = { 0,0 }; //結束標志
int Cross_Step[MAX][2]; //用來表示每一次變化的商人數和奴隸數 Cross_Step[step][0]代表商人
int SOLVE[5][2] = { {2,0}, {0,2},{0,1},{1,0}, {1,1} };//船上的人有五種情況
void DFS(Point Now)
{
if (Now == END) //列印路徑
{
for (int i = 1; i <= step; i++)
{
cout << "第" << i << "次過河,船上有" << Cross_Step[i][0] << "個商人," << Cross_Step[i][1] << "個仆人" << endl;
}
system("pause");
exit(0);
}
else if (Now.Businessman > 3 ||Now.Businessman<0||Now.Slave>3||Now.Slave<0) //出現了錯誤的方案
{
cout << "出現錯誤方案 " << step << endl;//(做測驗用)
step--;
return;
}
else if (step >= 2) //從第二次過河開始排重
{
if (Cross_Step[step - 1][0] == Cross_Step[step][0] && Cross_Step[step][1] == Cross_Step[step - 1][1])
{
cout << "出現重復 " << step << endl;//(做測驗用)
step--;
return;
}
}
else if ( (Now.Businessman>0 && Now.Businessman < Now.Slave) || ( Now.Businessman<3 && Now.Businessman > Now.Slave ) )//仆人造反
{
cout << "出現仆人造反 " << step << endl; //(做測驗用)
step--;
return;
}
else
{
int i;
Point temp;
for (i = 0; i < 5; i++) //嘗試五種做法
{
temp = Now;
step++;
cout << "第" << step << "次過河,第" << i+1 << "種方案" << endl;//(做測驗用)
if (step % 2 != 0)//從此岸到彼岸
{
temp.Businessman -= SOLVE[i][0];
temp.Slave -= SOLVE[i][1];
}
else //回來
{
temp.Businessman += SOLVE[i][0];
temp.Slave += SOLVE[i][1];
}
Cross_Step[step][0] = SOLVE[i][0];
Cross_Step[step][1] = SOLVE[i][1];
DFS(temp);
}
}
}
//int SOLVE[5][2] = { {2,0}, {0,2},{0,1},{1,0}, {1,1} };//船上的人有五種情況
int main()
{
Point Begin ;
Begin.Businessman = Begin.Slave = 3;
DFS(Begin);
cout << "沒有解決辦法!" << endl;
system("pause");
return 0;
}
運行截圖:
uj5u.com熱心網友回復:
謝謝各位 已經解決了。uj5u.com熱心網友回復:
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/41210.html
標籤:C++ 語言
上一篇:C++學生成績管理系統
下一篇:求救
