Need help modifying this code to add to my code. My code creates a grid but does not check if a word exists or not yet. Also, it should be user interface, user types in word, and computer outputs yes or no.
// C++ program to check if the word
// exists in the grid or not
#include <bits/stdc++.h>
using namespace std;
#define r 4
#define c 5
// Function to check if a word exists in a grid
// starting from the first match in the grid
// level: index till which pattern is matched
// x, y: current position in 2D array
bool findmatch(char mat[r], string pat, int x, int y,
int nrow, int ncol, int level)
{
int l = pat.length();
// Pattern matched
if (level == l)
return true;
// Out of Boundary
if (x < 0 || y < 0 || x >= nrow || y >= ncol)
return false;
// If grid matches with a letter while
// recursion
if (mat[x][y] == pat[level]) {
// Marking this cell as visited
char temp = mat[x][y];
mat[x][y] = '#';
// finding subpattern in 4 directions
bool res = findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) |
findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) |
findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) |
findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1);
// marking this cell
// as unvisited again
mat[x][y] = temp;
return res;
}
else // Not matching then false
return false;
}
// Function to check if the word exists in the grid or not
bool checkMatch(char mat[r], string pat, int nrow, int ncol)
{
int l = pat.length();
// if total characters in matrix is
// less then pattern lenghth
if (l > nrow * ncol)
return false;
// Traverse in the grid
for (int i = 0; i < nrow; i++) {
for (int j = 0; j < ncol; j++) {
// If first letter matches, then recur and check
if (mat[i][j] == pat[0])
if (findmatch(mat, pat, i, j, nrow, ncol, 0))
return true;
}
}
return false;
}
// Driver Code
int main()
{
char grid[r] = { "axmy",
"bgdf",
"xeet",
"raks" };
// Function to check if word exists or not
if (checkMatch(grid, "geeks", r, c))
cout << "Yes";
else
cout << "No";
return 0;
}
This is my code:
# include <stdio.h>
# include <math.h>
# include <stdlib.h>
int x;
int y;
char grid [10] [10];
int z;
int j;
int main()
{
// declare array with alphabet
char alphabet[26] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z' };
printf ("Insert the width (x) and height (y) of the grid \n");
scanf ("%d %d", &x, &y);
for (z = 0; z < x; z++)
{
for (j=0; j < y; j++)
{
// print letters instead of dots
grid [z] [j] = alphabet[rand() % 26];
}
}
for (z = 0; z < x; z++)
{
for (j=0; j < y; j++)
{
printf ("%c", grid [z] [j]);
}
printf ("\n");
}
}