Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3 × 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.
Input
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).
Output
Print one of the six verdicts: first, second, illegal, the first player won, the second player won or draw.
Example
Input
X0X
.0.
.X.
Output
second
题意: X,0游戏,在一个3*3的棋盘上,先手下X,后手下0,先使棋子三子连珠为胜者,(横竖,斜皆可)
输入一个棋局,输出,先手胜,后手胜,平局,先手下,后手下,非法棋局
非法情况有很多,于是我先考虑
******************************先手胜的情况
条件1,X三子连珠 2,X是最后一步使得三子连珠
进一步简化,1 ,X三子连珠 2 X的步数比0的步数多一
同理
*******************************后手胜的条件
1,0三子连珠 2 X的步数与0的步数相等
**********************************再看平局
条件 1棋局被下满,2未出现X或0三子连珠,3(划重点)X==5,0==4(否则算非法)
剩余先后手下和非法情况
***********************************先手下,
X的步数=0的步数(否则非法)
************************************后手下,
X的步数=0的步数+1(否则非法)
其余情况均为非法
################可见重点有二
1检测三星连珠,2统计某字符的个数
据此思路写程序,如下
#include<stdio.h>
char map[3][3];
int count(char a)//统计字符. 0 X的个数
{
int s=0;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(a==map[i][j])
s++;
return s;
}
int jude(char a)//判断是否初现X/0三子连珠
{
int i,j;
for(i=0;i<3;i++)//横竖
{
for(j=0;j<3;j++)
if(map[i][j]!=a)
break;
if(j==3)
return 1;
for(j=0;j<3;j++)
if(map[j][i]!=a)
break;
if(j==3)
return 1;
}
for(i=0;i<3;i++)//斜
{
if(map[i][i]!=a)
break;
}
if(i==3)
return 1;
for(i=0;i<3;i++)//斜2
{
if(map[i][2-i]!=a)
break;
}
if(i==3)
return 1;
return 0;
}
int main()
{
for(int i=0;i<3;i++)
scanf("%s",map[i]);
if(jude('X')&&jude('0'))//X&0胜
printf("illegal\n");
else if(jude('X'))//X三子连珠
{
if(count('X')==count('0')+1)
printf("the first player won\n");
else
printf("illegal\n");
}
else if(jude('0'))
{
if(count('0')==count('X'))
printf("the second player won\n");
else
printf("illegal\n");
}
else
{
if(count('.')==0)//棋盘下满
{
if(count('0')+1==count('X'))
printf("draw\n");
else
printf("illegal\n");
}
else
{
if(count('X')==count('0'))
printf("first\n");
else if(count('X')==count('0')+1)
printf("second\n");
else
printf("illegal\n");
}
}
return 0;
}