Code:
/* Search the 2 Dimension array, outward from any square.
Adak, May 20th, 2010.
status: ok in minimal testing
*/
#include <stdio.h>
#define RNUM 9
#define CNUM 9
void foundOne(int r, int c);
void showIt(int num[RNUM][CNUM]);
void search(int num[RNUM][CNUM], int r, int c, int rad);
int main() {
int i, j, r, c, rad;
int num[RNUM][CNUM] = {
{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, 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, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0}
};
printf("\n\n");
for(r= 0;r< RNUM; r++) {
for(c= 0;c< CNUM; c++) {
for(rad=1; rad<RNUM; rad++) {
num[r][c] = 9;
search(num, r, c, rad);
showIt(num);
getch();
for(i=0;i<RNUM;i++) {
for(j=0;j<CNUM;j++)
num[i][j] = 0;
}
}
}
}
printf("\n\n\t\t\t press enter when ready");
i = getchar(); ++i;
return 0;
}
/* foundOne() is not used, but would show where a value
you were searching for, was found.
*/
void foundOne(int r, int c) {
printf("\nfound a digit at num[%d][%d]", r, c);
}
/* search() is the heart of the program. It "walks" around
any square in the array, in increasing radii.
*/
void search(int num[RNUM][CNUM], int r, int c, int rad) {
int r1, c1;
for(r1=r-rad, c1=c-rad; c1 <= c+rad; c1++) { //top row
if(r1 < 0 || c1 < 0 || r1 >= RNUM || c1 >= CNUM)
continue;
num[r1][c1] = rad;
//if(num[r1][c1]) foundOne(r1,c1);
}
for(++r1, --c1; r1 <= r+rad; r1++) { //right side, going down
if(r1 < 0 || c1 < 0 || r1 >= RNUM || c1 >= CNUM)
continue;
num[r1][c1] = rad;
//if(num[r1][c1]) foundOne(r1,c1);
}
for(--c1, --r1; c1 >= c-rad; c1--) { //bottom row, going left
if(r1 < 0 || c1 < 0 || r1 >= RNUM || c1 >= CNUM)
continue;
num[r1][c1] = rad;
//if(num[r1][c1]) foundOne(r1,c1);
}
for(--r1, ++c1; r1 > r-rad; r1--) { //left side, going up, and minus 1 sqr
if(r1 < 0 || c1 < 0 || r1 >= RNUM || c1 >= CNUM)
continue;
num[r1][c1] = rad;
//if(num[r1][c1]) foundOne(r1,c1);
}
}
/* shows what squares have been visited by the latest search */
void showIt(int num[RNUM][CNUM]) {
int r, c;
printf("\n\n");
for(r=0;r<RNUM; r++) {
for(c=0;c<CNUM; c++) {
printf("%d ", num[r][c]);
}
printf("\n");
}
}