Here's something to study.
Code:
#include<stdio.h>
#include<stdlib.h>
#define GRID_W 10
#define GRID_H 10
int isValidPos(int row, int col) {
return row >= 0 && row < GRID_H &&
col >= 0 && col < GRID_W;
}
int allowed(char grid[GRID_H][GRID_W], int row, int col, int deltar, int deltac, const char *word) {
int result = 1;
while ( result && *word ) {
result = isValidPos(row, col); // it's in the grid
result = result && (grid[row][col] == ' ' || grid[row][col] == *word); // the cell is free, or matches
if ( result ) {
row += deltar; // next pos in the chosen dir
col += deltac;
word++; // next char
}
}
return result;
}
void addWord(char grid[GRID_H][GRID_W], int row, int col, int deltar, int deltac, const char *word) {
if ( allowed(grid, row, col, deltar, deltac, word) ) {
while ( *word ) {
grid[row][col] = *word;
row += deltar; // next pos in the chosen dir
col += deltac;
word++; // next char
}
}
}
void initGrid(char grid[GRID_H][GRID_W]) {
for ( int r = 0 ; r < GRID_H ; r++ ) {
for ( int c = 0 ; c < GRID_W ; c++ ) {
grid[r][c] = ' ';
}
}
}
void printGrid(const char grid[GRID_H][GRID_W]) {
for ( int r = 0 ; r < GRID_H ; r++ ) {
for ( int c = 0 ; c < GRID_W ; c++ ) {
putchar(grid[r][c]);
}
putchar('\n');
}
}
int main ()
{
char grid[GRID_H][GRID_W];
initGrid(grid);
addWord(grid, 0, 0, 1, 1, "hello"); // diagonal hello
addWord(grid, 4, 3, 0, 1, "world"); // horizontal world through end of hello
addWord(grid, 9, 9, -1, -1, "bye");
printGrid(grid);
return 0;
}
$ gcc foo.c
$ ./a.out
h
e
l
l
world
e
y
b