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 |
#include <iostream> #include <cstdio> #include <cstring> using namespace std; char board[3][3]; int main(){ memset(board, 0, sizeof(board)); string line; for (int i = 0; i < 3; i++) { cin >> line; if (line.size() > 3) { cout << "illegal" << endl; return 0; } for (int j = 0; j < 3; j++) { board[i][j] = line[j]; } } //judge legal(partial) int oCnt = 0,xCnt = 0; for (int i = 0;i < 3; i++) { for (int j = 0; j < 3; j++) { switch (board[i][j]) { case '0': oCnt++; break; case 'X': xCnt++; break; default: break; } } } if (!(xCnt - oCnt == 1 || xCnt == oCnt)) { cout << "illegal" << endl; return 0; } //judge who is next int nextis = 0; if (oCnt == xCnt) { nextis = 1; }else{ nextis = 2; } //judge game completion bool oWin = false,xWin = false; for (int r = 0; r < 3; r++) { if (board[r][0] == board[r][1] && board[r][1] == board[r][2] && board[r][0] == board[r][2]) { if (board[r][0] == '0') { oWin = true; } if (board[r][0] == 'X') { xWin = true; } } if (board[0][r] == board[1][r] && board[1][r] == board[2][r] && board[2][r] == board[0][r]) { if (board[0][r] == '0') { oWin = true; } if (board[0][r] == 'X') { xWin = true; } } } if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] == board[2][2]) { if (board[0][0] == '0') { oWin = true; } if (board[0][0] == 'X') { xWin = true; } } if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] == board[2][0]) { if (board[1][1] == '0') { oWin = true; } if (board[1][1] == 'X') { xWin = true; } }//judge complete if (xWin && oWin) { cout << "illegal" << endl; return 0; }//cannot both win else if (!xWin && !oWin) { if (xCnt+oCnt == 9) { cout << "draw" << endl; return 0; } }//if full,good game else if(xWin && xCnt > oCnt){ cout << "the first player won" << endl; return 0; } else if(oWin && xCnt == oCnt){ cout << "the second player won" << endl; return 0; }else{ cout << "illegal" << endl; return 0; } //game still not end if (nextis == 1) { cout << "first" << endl; return 0; } if (nextis == 2) { cout << "second" << endl; return 0; } return 0; } |
模拟题,这个题我WA了一下的原因是忘记了X的数量始终比O多一个,即使是赢了,也要是在棋盘合法的前提下。