Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a3 × 3 grid (one player always draws crosses, the other — noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the game is finished. The player who draws crosses goes first. If the grid is filled, but neither Xs, nor 0s form the required line, a draw is announced.
You are given a 3 × 3 grid, each grid cell is empty, or occupied by a cross or a nought. You have to find the player (first or second), whose turn is next, or print one of the verdicts below:
- illegal — if the given board layout can't appear during a valid game;
- the first player won — if in the given board layout the first player has just won;
- the second player won — if in the given board layout the second player has just won;
- draw — if the given board layout has just let to a draw.
The input consists of three lines, each of the lines contains characters ".", "X" or "0" (a period, a capital letter X, or a digit zero).
Print one of the six verdicts: first, second, illegal, the first player won, the second player won or draw.
X0X .0. .X.
second
题意两个人交替在一个3x3的棋盘上下棋
一个人先走用X标记另一个人后走用0标记
没走过的用.标记
要判断给定局面属于非法illegal
或者某人获胜
或者轮某人走
或者平局
这里可以想到如果不是 1后走的与先走的步数一样多,
2后走的比先走的少一步
的局面都是非法的
另外这个游戏在有一个人的棋3连的时候就应当结束
所以先走的人赢且合法必须是先走的多一步
后走的人赢且合法必须是两人步数相同
都赢的局面肯定不合法
其他的靠穷举和计数就可以解决了
特别注意判断子的环节要特别区别下.
#include <iostream>
#include <stdio.h>
using namespace std;
char ti[5][5];
int main()
{
for(int i=1;i<=3;i++)
scanf("%s",ti[i]+1);
int nd=0,nx=0,no=0;
for(int i=1;i<=3;i++)
for(int j=1;j<=3;j++)
{
if(ti[i][j]=='.')
nd++;
else if(ti[i][j]=='X')
nx++;
else
no++;
}
//cout<<nd<<" "<<nx<<" "<<no<<endl;
if(!((no+1)==nx||no==nx)) //非法
{
printf("illegal\n");
return 0;
}
int f=0;
for(int i=1;i<=3;i++) //某一行列
{
if(ti[i][1]!='.'&&ti[i][1]==ti[i][2]&&ti[i][1]==ti[i][3])
{
if(!f)
f=ti[i][1]=='X'?1:2;
else if(f!=(ti[i][1]=='X'?1:2))
f=3;
}
if(ti[1][i]!='.'&&ti[1][i]==ti[2][i]&&ti[1][i]==ti[3][i])
{
if(!f)
f=ti[1][i]=='X'?1:2;
else if(f!=(ti[1][i]=='X'?1:2))
f=3;
}
}
if((ti[1][1]!='.'&&ti[1][1]==ti[2][2]&&ti[1][1]==ti[3][3])||(ti[3][1]!='.'&&ti[3][1]==ti[2][2]&&ti[3][1]==ti[1][3])) //对角线
{
if(!f)
f=ti[2][2]=='X'?1:2;
else if(f!=(ti[2][2]=='X'?1:2))
f=3;
}
if(f==1)
{
if(no+1==nx)
printf("the first player won\n");
else
printf("illegal\n");
return 0;
}
else if(f==2)
{
if(no==nx)
printf("the second player won\n");
else
printf("illegal\n");
return 0;
}
else if(f==3)
{
printf("illegal\n");
return 0;
}
if(nd==0)
{
printf("draw\n");
return 0;
}
if(nx==no)
printf("first\n");
else
printf("second\n");
return 0;
}