Monday, June 6, 2011

10363 - Tic Tac Toe


#include<stdio.h>
#include<string.h>

char B[4][4];
bool IsValid();
bool IsWinner(char ch);

int main()
{
    int t,i;
    //freopen("in.txt","r",stdin);
    scanf("%d\n",&t);

    while(t--)
    {
        for(i=0;i<4;i++)
            gets(B[i]);

        if(IsValid())
            printf("yes\n");
        else
            printf("no\n");
    }
    return 0;
}

bool IsValid()
{
    int nx=0,no=0,i,j;
    bool xw,ow;

    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            switch(B[i][j])
            {
            case 'X':nx++;break;
            case 'O':no++;break;
            }
        }
    }

    if(no>nx)return false;
    if(nx-no>1)return false;

    xw = IsWinner('X');
    ow = IsWinner('O');

    if(ow&&nx>no)
        return false;

    if(xw&&nx==no)
        return false;

    if(xw&&ow)
        return false;
    return true;
}

bool IsWinner(char ch)
{
    //Row Check
    if(B[0][0]==ch&&B[0][1]==ch&&B[0][2]==ch)return true;
    if(B[1][0]==ch&&B[1][1]==ch&&B[1][2]==ch)return true;
    if(B[2][0]==ch&&B[2][1]==ch&&B[2][2]==ch)return true;

    //Column Check
    if(B[0][0]==ch&&B[1][0]==ch&&B[2][0]==ch)return true;
    if(B[0][1]==ch&&B[1][1]==ch&&B[2][1]==ch)return true;
    if(B[0][2]==ch&&B[1][2]==ch&&B[2][2]==ch)return true;

    //Diagonal Check
    if(B[0][0]==ch&&B[1][1]==ch&&B[2][2]==ch)return true;
    if(B[0][2]==ch&&B[1][1]==ch&&B[2][0]==ch)return true;
    return false;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.