动态规划做多了也想做一点别的题来换一换口味,就写一个模拟题好了。
这个题我感觉还是挺好写的,check是一个重载函数,假如给了dir的话,就判断在dir的方向上是不是合法,假如没有给dir的话,就默认在所有8个方向上判定是不是合法,最后返回一个bool值
change用于改变局面,print打印整个局面,turn用于表示current player,black为2,white为1,在棋盘上也是这样。
dx和dy用于表示8个方向。
写到PE就直接找题解了,懒得在格式上纠缠了,发现原来是在M操作之后输出数据的时候要占两位。
#include <iostream>
#include <string>
#include <cstring>
#include <iomanip>
using namespace std;
//black for 2,white for 1;
int board[8][8],turn,t,num[2];
const int dx[]{0,1,0,-1,1,1,-1,-1},dy[]{1,0,-1,0,1,-1,1,-1};
void print(),change(int x,int y);
bool check(int x,int y),change(int x,int y,int dir),first;
string ord;
char c;
inline int f1(char c){
switch(c){
case '-':
return 0;
case 'W':
++num[0];
return 1;
case 'B':
++num[1];
return 2;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin>>t;
while(t--){
if(first)
cout<<endl;
else
first=true;
for(int i=0;i<8;++i)
for(int j=0;j<8;++j){
cin>>c;
board[i][j]=f1(c);
}
cin>>c;
turn=f1(c);
num[c=='B']--;
while(cin>>ord){
if(ord[0]=='M'){
int x=ord[1]-'1',y=ord[2]-'1';
if(check(x,y))
change(x,y);
else
turn=3-turn,change(x,y);
num[turn-1]++;
board[x][y]=turn;
turn=3-turn;
cout<<"Black - "<<setw(2)<<num[1]<<" White - "<<setw(2)<<num[0]<<endl;
}
else if(ord[0]=='L'){
bool flag=true,te=false;;
for(int i=0;i<8;++i)
for(int j=0;j<8;++j)
if(!board[i][j]&&check(i,j)){
flag=false;
if(!te)
cout<<'('<<i+1<<','<<j+1<<")",te=true;
else
cout<<" ("<<i+1<<','<<j+1<<")";
}
if(flag)
cout<<"No legal move.\n";
else
cout<<endl;
}
else{
print();
break;
}
}
memset(board,0,sizeof board);
num[0]=num[1]=0;
}
}
bool check(int x,int y){
bool flag=false;
for(int i=0;i<8;++i,flag=false)
for(int j=1;x+dx[i]*j>=0&&x+dx[i]*j<8&&y+dy[i]*j>=0&&y+dy[i]*j<8;++j)
if(j==1&&board[x+dx[i]][y+dy[i]]!=3-turn)
break;
else if(j==1)
flag=true;
else if(flag&&board[x+j*dx[i]][y+j*dy[i]]==turn)
return true;
else if(flag&&board[x+j*dx[i]][y+j*dy[i]]==0)
break;
return false;
}
bool check(int x,int y,int dir){
bool flag=false;
for(int j=1;x+dx[dir]*j>=0&&x+dx[dir]*j<8&&y+dy[dir]*j>=0&&y+dy[dir]*j<8;++j)
if(j==1&&board[x+dx[dir]][y+dy[dir]]!=3-turn)
break;
else if(j==1)
flag=true;
else if(flag&&board[x+j*dx[dir]][y+j*dy[dir]]==turn)
return true;
else if(flag&&board[x+j*dx[dir]][y+j*dy[dir]]==0)
return false;
return false;
}
void change(int x,int y){
for(int i=0;i<8;++i)
if(check(x,y,i))
for(int j=1;board[x+dx[i]*j][y+dy[i]*j]==3-turn;++j)
board[x+dx[i]*j][y+dy[i]*j]=turn,num[turn-1]++,num[2-turn]--;
}
void print(){
for(int i=0;i<8;++i){
for(int j=0;j<8;++j)
if(board[i][j]==0)
cout<<'-';
else if(board[i][j]==1)
cout<<'W';
else
cout<<'B';
cout<<endl;
}
}