forked from mohitsh/SPOJ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoe2.cpp
131 lines (131 loc) · 2.34 KB
/
toe2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// 2008-08-04
#include <iostream>
#include <string>
using namespace std;
int XWins(char s[3][3])
{
int c=0;
if (s[0][0]=='X'&&s[1][0]=='X'&&s[2][0]=='X')
c++;
if (s[0][1]=='X'&&s[1][1]=='X'&&s[2][1]=='X')
c++;
if (s[0][2]=='X'&&s[1][2]=='X'&&s[2][2]=='X')
c++;
if (s[0][0]=='X'&&s[0][1]=='X'&&s[0][2]=='X')
c++;
if (s[1][0]=='X'&&s[1][1]=='X'&&s[1][2]=='X')
c++;
if (s[2][0]=='X'&&s[2][1]=='X'&&s[2][2]=='X')
c++;
if (s[0][0]=='X'&&s[1][1]=='X'&&s[2][2]=='X')
c++;
if (s[0][2]=='X'&&s[1][1]=='X'&&s[2][0]=='X')
c++;
return c;
}
int OWins(char s[3][3])
{
int c=0;
if (s[0][0]=='O'&&s[1][0]=='O'&&s[2][0]=='O')
c++;
if (s[0][1]=='O'&&s[1][1]=='O'&&s[2][1]=='O')
c++;
if (s[0][2]=='O'&&s[1][2]=='O'&&s[2][2]=='O')
c++;
if (s[0][0]=='O'&&s[0][1]=='O'&&s[0][2]=='O')
c++;
if (s[1][0]=='O'&&s[1][1]=='O'&&s[1][2]=='O')
c++;
if (s[2][0]=='O'&&s[2][1]=='O'&&s[2][2]=='O')
c++;
if (s[0][0]=='O'&&s[1][1]=='O'&&s[2][2]=='O')
c++;
if (s[0][2]=='O'&&s[1][1]=='O'&&s[2][0]=='O')
c++;
return c;
}
int NumberOfX(char r[3][3])
{
int i,j;
int c=0;
for (i=0; i<3; i++)
for (j=0; j<3; j++)
if (r[i][j]=='X')
c++;
return c;
}
int NumberOfO(char r[3][3])
{
int i,j;
int c=0;
for (i=0; i<3; i++)
for (j=0; j<3; j++)
if (r[i][j]=='O')
c++;
return c;
}
int main()
{
int j,k;
char s[3][3];
for(;;)
{
for (j=0; j<3; j++)
for (k=0; k<3; k++)
{
cin >> s[k][j];
if (s[k][j]=='e')
return 0;
}
//if X wins, there must be one more X than the # of Os
//if O wins, there must be the same number of Os as Xs
int Xw=XWins(s);
int Ow=OWins(s);
int Xs=NumberOfX(s);
int Os=NumberOfO(s);
if (Xw&&Ow||Os>Xs||Os<Xs-1||Xs==Os&&Xw||Xs==Os+1&&Ow||!(Xw||Ow||(Xs+Os==9)))
cout << "invalid";
else if (Xw)
{
bool b=true;
for (j=0; j<3; j++)
for (k=0; k<3; k++)
{
if (s[j][k]!='X')
continue;
s[j][k]='.';
int z=XWins(s);
if (z==0)
b=true;
s[j][k]='X';
}
if (b)
cout << "valid";
else
cout << "invalid";
}
else if (Ow)
{
bool b=false;
for (j=0; j<3; j++)
for (k=0; k<3; k++)
{
if (s[j][k]!='O')
continue;
s[j][k]='.';
int z=XWins(s);
if (z==0)
b=true;
s[j][k]='O';
}
if (b)
cout << "valid";
else
cout << "invalid";
}
else
cout << "valid";
cout << endl;
}
return 0;
}