Code:
#include <stdio.h>
#define XSIZE 10
#define YSIZE 10
#define O(y,x) ((x)>-1&&(x)<(XSIZE)&&(y)>-1&&(y)<(YSIZE))
#define y__ y-1
#define _y_ y
#define __y y+1
#define __x x+1
#define _x_ x
#define x__ x-1
#define BAD(x,y,z) \
(\
(O(_y_,x__)?z[_y_][x__]:0)+\
(O(__y,x__)?z[__y][x__]:0)+\
(O(__y,_x_)?z[__y][_x_]:0)+\
(O(__y,__x)?z[__y][__x]:0)+\
(O(_y_,__x)?z[_y_][__x]:0)+\
(O(y__,__x)?z[y__][__x]:0)+\
(O(y__,_x_)?z[y__][_x_]:0)+\
(O(y__,x__)?z[y__][x__]:0) \
)
int main ( void )
{
int matrix[YSIZE][XSIZE]={
{0,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,1,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,1,0,0,0,0,0,0,0},
{0,1,0,0,0,0,0,0,0,0},
{1,0,0,0,0,0,0,0,0,0}
};
int x, y;
/* draw it */
for( y = 0; y < YSIZE; y++ )
{
for( x = 0; x < XSIZE; x++ )
printf("%d", matrix[y][x] );
printf("\n");
}
printf("Enter to Continue...\n");
getchar( );
/* results */
for( y = 0; y < YSIZE; y++ )
for( x = 0; x < XSIZE; x++ )
if( matrix[y][x] )
{
printf("On row %d, cell %d, encountered %d.\n", y, x, matrix[y][x] );
printf("Check: %d, is %svalid.\n", BAD(y,x,matrix), BAD(y,x,matrix?"in":"" );
}
return 0;
}
/*
0100000000
0000000000
0000010000
0000000000
0100000000
0000000000
0000000000
0010000000
0100000000
1000000000
Enter to Continue...
On row 0, cell 1, encountered 1.
Check: 0, is valid.
On row 2, cell 5, encountered 1.
Check: 0, is valid.
On row 4, cell 1, encountered 1.
Check: 0, is valid.
On row 7, cell 2, encountered 1.
Check: 1, is invalid.
On row 8, cell 1, encountered 1.
Check: 2, is invalid.
On row 9, cell 0, encountered 1.
Check: 1, is invalid.
*/
Nice and simple. (I was going to make it a nifty picture, but you'll have to settle for this instead.) And yes, I have a function instead of a macro for you who are picky about macros. But macros are funner.