I'm writing a tic-tac-toe game in C where the user chooses the size of the grid. The grid is a 2D array.
I'm having trouble efficiently checking for a win. This is my current idea:
for(int y = 0; y < gridSize; y++)
{
int lineTotal = 0;
for(int x = 0; x < gridSize; x++)
{
if (grid[x][y] == grid[0][y])
{
lineTotal++;
if (lineTotal == gridSize && grid[x][y] == playersLetter)
{
return 1;
}
}
}
}
Which checks every row for a full line. If I want to check each column, I have to swap x
and y
re-do each loop. I also have to do another loop to check the diagonals, though that's not too hard seeing as there are only two.
My problem is I want to limit the amount of iterations of all the loops to gridSize^2
.