Need help to edit this code to allow user to find words in the grid that are touching horizontally, vertically, and diagonally adjacent. For example, the board:
Q W E R T
A S D F G
Z X C V B
Y U A O P
G H J K L
contains the magic words WAS, WAXY, JOB.
# include <stdio.h>
# include <math.h>
# include <stdlib.h>
def find_in_grid(word):
for K = [0:nrows-1]:
for L = [0:ncols-1]:
if can_form_word(K, L, word):
returntruereturnfalse
def can_form_word(x, y, word):
if word.is_empty(): //base case, can always form ''
returntrueif grid[x][y] == word[0]: //found first character
for K = [-1:1]:
for L = [-1:1]:
if can_form_word(x+K, y+L, word[1:]): //check the neighbours for the rest
returntruereturnfalse
it's missing bound checking
you may use a bigger matrix, and fill the border with an invalid value, such that once it reaches a border the function will end
also, it allows to use the same cell several times and even never moving, if that's not allowed you need to mark the visited cell somehow.
*diagonals were not allowed in classic boggle. if you care.
it may be more efficient to generate every possible word from your grid up front, and then look for each one using the rules, rather than look at each letter and then each pair and then each surviving triplet and then each surviving quad.. etc .. over and over. I haven't worked out if that is true or not, but adding the diagonal dimension to it makes me lean that way.
It's similar to boggle but not exactly like boggle, so diagonally is allowed. The grid has to be random letters each time, its not constant so I can't do all words possible.
yes, you can :) I am unsure if its the best way, but you certainly can look up all the possible words first. Or you can build up and check each thing you cook up to see if its a word. Both work, not sure which is faster. You wouldn't make all the permutations. … something like char letters[256] = 0; for each letter in the grid, increment letters [letter] eg if you have 'a' then letters['a']++. Now that you have it in this form, iterate it from 'a' to 'z' … choose the letter you are on as your starting letter if its in the array. pull all the words that start with that from your dictionary into a sorted list. grab the first word, check letter by letter if letters[letter] is true. If its true for all the letters, the word is a candidate. Its a lot of iteration, but its CHEAP iteration.... then take all the candidates and see if you can make them by forming a path in the grid (this is expensive but you have weeded out a lot of trash this way, and what is left will go quickly, I think?)