/* Complete TicTacToe */ #include <stdio.h> #define DEBUG int grid[3][3]; int checkwin(int row, int col, int row_step, int col_step, int x_or_o) { int i; int sum = 0; for (i = 0; i < 3; i++) { if (grid[row][col] == x_or_o) sum++; row += row_step; col += col_step; } // The same symbol 3 times in a row/column/diagonal is a win if (sum == 3) return 1; else return 0; } int main () { int gamecount, i, row, col; int xwins, owins; // The first integer indicates how many games we will examine scanf(" %d", &gamecount); // Read each game from the input and determine its outcome for (i = 0; i < gamecount; i++) { // Re-initialize the number of X and O wins for each game xwins = 0; owins = 0; // Read in the 3 by 3 grid // It doesn't matter if input is in row major or column major order for (row = 0; row < 3; row++) { for (col = 0; col < 3; col++) { scanf(" %d", &grid[row][col]); } } #ifdef DEBUG printf("\n"); for (row = 0; row < 3; row++) { for (col = 0; col < 3; col++) { printf("%c", grid[row][col] ? 'X' : 'O'); } printf("\n"); } printf (":%d:", i); #endif // Check for X's or O's in any rows for (row = 0; row < 3; row++) { xwins += checkwin(row, 0, 0, +1, 1); owins += checkwin(row, 0, 0, +1, 0); } // Check for X's or O's in any columns for (col = 0; col < 3; col++) { xwins += checkwin(0, col, +1, 0, 1); owins += checkwin(0, col, +1, 0, 0); } // Check for X's along the diagonals xwins += checkwin(0, 0, +1, +1, 1); xwins += checkwin(0, 2, +1, -1, 1); // Check for O's along the diagonals owins += checkwin(0, 0, +1, +1, 0); owins += checkwin(0, 2, +1, -1, 0); // Determine who wins if ((xwins == 0 && owins == 0) || (xwins > 1) || (owins > 1)) printf("No One Wins\n"); else if (xwins == 1 && owins == 0) printf("X Wins\n"); else if (xwins == 0 && owins == 1) printf("O Wins\n"); else printf("Both Win\n"); } } Return to Problem Index |