Code:
#include <stdio.h>
#define MAX 5
void print_board ( char board[][MAX] ) {
int r, c;
for ( r = 0 ; r < MAX ; r++ ) {
for ( c = 0 ; c < MAX ; c++ ) {
printf( "%c", board[r][c] );
}
printf( "\n" );
}
}
void check_for_line ( char board[][MAX], int start_r, int start_c ) {
// at this point, we can go in 8 possible directions
// and we already know that board[start_r][start_c] is an 'X'
int r1, c1;
// r1 = -1 is previous row, 0 is current row, +1 is next row
for ( r1 = -1 ; r1 <= 1 ; r1++ ) {
for ( c1 = -1 ; c1 <= 1 ; c1++ ) {
int i, r, c;
// both zeros mean we don't move anywhere, so skip this case
if ( r1 == 0 && c1 == 0 ) continue;
for ( i = 1 ; i < 4 ; i++ ) {
// the next square, in our chosen direction
r = start_r + r1 * i;
c = start_c + c1 * i;
// check that we are still on the board - exit if we are not
if ( r < 0 || r >= MAX ) break;
if ( c < 0 || c >= MAX ) break;
// check that we still have a matching piece - exit if not
if ( board[r][c] != 'X') break;
}
// got 4 in a row - report the good news!
if ( i == 4 ) {
printf( "Line found starting at %d,%d ending at %d,%d\n",
start_r, start_c, r, c );
}
}
}
}
// check every position of the board, to see if it's the start of a line
void check ( char board[][MAX] ) {
int r, c;
for ( r = 0 ; r < MAX ; r++ ) {
for ( c = 0 ; c < MAX ; c++ ) {
if ( board[r][c] == 'X' ) {
check_for_line( board, r, c );
}
}
}
}
int main ( ) {
// example board with 1,2,3,4 length lines of X
char board[MAX][MAX] = {
{ '.', '.', '.', '.', 'X' },
{ 'X', 'X', '.', 'X', '.' },
{ '.', '.', 'X', '.', '.' },
{ '.', 'X', 'X', '.', '.' },
{ '.', '.', 'X', '.', 'X' },
};
print_board( board );
check( board );
return 0;
}