您的位置:首页 > 移动开发 > 微信开发

小程序

2013-10-28 11:02 134 查看
#include <iostream>
using namespace std;

//enum Type {AIR, WHITE, BLACK};

int A[10][10] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 2, 0, 0, 0, 0, 0,
0, 0, 0, 2, 1, 2, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
bool B[10][10];
int eatCount = 0;

void initFlagMatrix()
{
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
B[i][j] = false;
}
}

bool hasAir(int i, int j, int type)
{
if(A[i][j] == 0) return true;
if(A[i][j] != type) return false;
eatCount++;
B[i][j] = true;
if(i > 0 && !B[i-1][j] && hasAir(i-1, j, type)) return true;
else if(i < 9 && !B[i+1][j] && hasAir(i+1, j, type)) return true;
else if(j > 0 && !B[i][j-1] && hasAir(i, j-1, type)) return true;
else if(j < 9 && !B[i][j+1] && hasAir(i, j+1, type)) return true;
else return false;
}

//将与A[i][j]相连的相同类型的棋子全部吃掉
void eatChess(int i, int j, int type)
{
if(A[i][j] != type) return;
A[i][j] = 0;	//eat the chess
if(i > 0) eatChess(i-1, j, type);
if(i < 9) eatChess(i+1, j, type);
if(j > 0) eatChess(i, j-1, type);
if(j < 9) eatChess(i, j+1, type);
}

//check the whole chess of type is there any chess if out of air
bool hasAirOfType(int type, int &p, int &q)
{
for(int i  = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
if(A[i][j] != type || B[i][j]) continue;
eatCount = 0;
if(!hasAir(i, j, type))
{
p = i, q = j;
return false;
}
}
}
return true;
}

//get the chess that has been eaten when we put a chess of type on position [i,j]
int eatenChesscount(int i, int j, int type)
{
initFlagMatrix();
bool self_hasAir = hasAir(i, j, type);
eatCount = 0;
int p = 0, q = 0;
int other_type = (type==1?2:1);
initFlagMatrix();
bool other_hasAir = hasAirOfType(other_type, p, q);

if(!self_hasAir && other_hasAir)
{
A[i][j] = 0;
return INT_MAX;	//suicide chess is not allowed
}
if(!other_hasAir)
{
eatChess(p, q, other_type);
if(other_type == 1) return eatCount;
else return 0-eatCount;
}
return 0;
}

void printChessState()
{
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
}

int main()
{
int i, j, type;
while(cin >> i >> j >> type)
{
if(A[i][j] != 0)
{
cout << INT_MAX << endl;
continue;
}
A[i][j] = type;
printChessState();
cout << eatenChesscount(i, j, type) << endl;
printChessState();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: