题目:有三个白子和三个黑子如下图布置:
○ ○ ○ . ● ● ●
游戏的目的是用最少的步数将上图中白子和黑子的位置进行交换:
● ● ● . ○ ○ ○
○ ○ ○ . ● ● ●
游戏的目的是用最少的步数将上图中白子和黑子的位置进行交换:
● ● ● . ○ ○ ○
游戏的规则是:(1)一次只能移动一个棋子; (2)棋子可以向空格中移动,也可以跳过一个对方的棋子进入空格,但不能向后跳,也不能跳过两个子。请用计算机实现上述游戏。
/*
题目:有三个白子和三个黑子如下图布置:
○ ○ ○ . ● ● ●
游戏的目的是用最少的步数将上图中白子和黑子的位置进行交换:
● ● ● . ○ ○ ○
by as1138 2013-05-25
*/
#include <iostream>
#include <list>
using namespace std;
#define WHITEPIECE 1
#define BLACKPIECE 2
#define NULLVALUE 0
#define MAPLEN 7
typedef struct stStatus
{
int m_data[MAPLEN];
}Status;
list<Status> g_listatus;//存储整个步骤
void GameStep(Status& st, int NullPos);
bool GameOver(Status& st);
int main()
{
Status ss = {1,1,1,0,2,2,2};
GameStep(ss,3);
return 0;
}
void GameStep(Status& st, int NullPos)
{
g_listatus.push_back(st);
if(GameOver(st))
{
list<Status>::iterator it = g_listatus.begin();
for(;it != g_listatus.end();++it)
{
for(int i=0; i<MAPLEN; ++i)
{
cout << it->m_data[i] << " ";
}
cout << endl;
}
return;
}
if((NullPos+1) < MAPLEN)//空格的右边第一个棋子判别
{
if(st.m_data[NullPos+1] == BLACKPIECE)
{
if((NullPos < 3)||(NullPos-1)>-1 && (st.m_data[NullPos-1] != BLACKPIECE))
{
st.m_data[NullPos] = BLACKPIECE;
st.m_data[NullPos+1] = NULLVALUE;
GameStep(st, NullPos+1);
}
}
}
if((NullPos+2) < MAPLEN)//空格的右边第二个棋子判别
{
if(st.m_data[NullPos+2] == BLACKPIECE)
{
if((NullPos < 3)||(NullPos-1)>-1 && (st.m_data[NullPos+1] != BLACKPIECE) && (st.m_data[NullPos-1] != BLACKPIECE))
{
st.m_data[NullPos] = BLACKPIECE;
st.m_data[NullPos+2] = NULLVALUE;
GameStep(st, NullPos+2);
}
}
}
if((NullPos-1) > -1)//空格的左边第一个棋子判别
{
if(st.m_data[NullPos-1] == WHITEPIECE)
{
if((NullPos > 3)||(NullPos+1) < MAPLEN && (st.m_data[NullPos+1] != WHITEPIECE))
{
st.m_data[NullPos] = WHITEPIECE;
st.m_data[NullPos-1] = NULLVALUE;
GameStep(st, NullPos-1);
}
}
}
if((NullPos-2) > -1)//空格的左边第二个棋子判别
{
if(st.m_data[NullPos-2] == WHITEPIECE)
{
if((NullPos > 3)||(NullPos+1) < MAPLEN && (st.m_data[NullPos+1] != WHITEPIECE) && (st.m_data[NullPos-1] != WHITEPIECE))
{
st.m_data[NullPos] = WHITEPIECE;
st.m_data[NullPos-2] = NULLVALUE;
GameStep(st, NullPos-2);
}
}
}
g_listatus.pop_back();
st = g_listatus.back();
return;
}
bool GameOver(Status& st)
{
if(st.m_data[3] == NULLVALUE)
{
return (st.m_data[0] + st.m_data[1] + st.m_data[2] == 6) ? true : false;
}
return false;
}