Check if a word exists in a grid or not - GeeksforGeeks

20 Jan, 2022
Given a 2D grid of characters and a word, the task is to check if that word exists in the grid or not. A word can be matched in 4 directions at any point.The 4 directions are, Horizontally Left and Right, Vertically Up and Down. Examples:  
Input:  grid[][] = {"axmy",
                    "bgdf",
                    "xeet",
                    "raks"};
Output: Yes

a x m y
b g d f
x e e t
r a k s

Input: grid[][] = {"axmy",
                   "brdf",
                   "xeet",
                   "rass"};
Output : No
Source: Microsoft Interview 
Approach: The idea used here is described in the steps below:  
Check every cell, if the cell has first character, then recur one by one and try all 4 directions from that cell for a match.
Mark the position in the grid as visited and recur in the 4 possible directions.
After recurring, again mark the position as unvisited.
Once all the letters in the word are matched, return true.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// 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 arraybool 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 notbool checkMatch(char mat[r], string pat, int nrow, int ncol){     int l = pat.length();     // if total characters in matrix is    // less then pattern length    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 Codeint 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; }
// Java program to check if the word// exists in the grid or notclass GFG{     static final int r = 4;static final int c = 4; // 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 arraystatic boolean findmatch(char mat[][], 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.charAt(level))    {         // Marking this cell as visited        char temp = mat[x][y];        mat[x][y] = '#';         // finding subpattern in 4 directions        boolean 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 notstatic boolean checkMatch(char mat[][], String pat, int nrow, int ncol){     int l = pat.length();     // if total characters in matrix is    // less then pattern length    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.charAt(0))                if (findmatch(mat, pat, i, j, nrow, ncol, 0))                    return true;        }    }    return false;} // Driver Codepublic static void main(String[] args){    char grid[][] = { "axmy".toCharArray(),                        "bgdf".toCharArray(),                        "xeet".toCharArray(),                        "raks".toCharArray() };     // Function to check if word exists or not    if (checkMatch(grid, "geeks", r, c))        System.out.print("Yes");    else        System.out.print("No");}} // This code is contributed by 29AjayKumar
# Python3 program to check if the word# exists in the grid or not r = 4c = 4 # 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 arraydef findmatch(mat, pat, x, y,              nrow, ncol, level) :     l = len(pat)     # Pattern matched    if (level == l) :        return True     # Out of Boundary    if (x < 0 or y < 0 or        x >= nrow or y >= ncol) :        return False     # If grid matches with a letter    # while recursion    if (mat[x][y] == pat[level]) :         # Marking this cell as visited        temp = mat[x][y]        mat[x].replace(mat[x][y], "#")         # finding subpattern in 4 directions        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].replace(mat[x][y], temp)        return res         else : # Not matching then false        return False # Function to check if the word# exists in the grid or notdef checkMatch(mat, pat, nrow, ncol) :     l = len(pat)     # if total characters in matrix is    # less then pattern length    if (l > nrow * ncol) :        return False     # Traverse in the grid    for i in range(nrow) :        for j in range(ncol) :             # 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 Codeif __name__ == "__main__" :     grid = ["axmy", "bgdf",            "xeet", "raks"]     # Function to check if word    # exists or not    if (checkMatch(grid, "geeks", r, c)) :        print("Yes")    else :        print("No") # This code is contributed by Ryuga
// C# program to check if the word// exists in the grid or notusing System; class GFG{     static readonly int r = 4;static readonly int c = 4; // 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 arraystatic bool findmatch(char [,]mat, 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 notstatic bool checkMatch(char [,]mat, String pat, int nrow, int ncol){     int l = pat.Length;     // if total characters in matrix is    // less then pattern length    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 Codepublic static void Main(String[] args){    char [,]grid = { {'a','x','m','y'},                    {'b','g','d','f'},                    {'x','e','e','t'},                    {'r','a','k','s'} };     // Function to check if word exists or not    if (checkMatch(grid, "geeks", r, c))        Console.Write("Yes");    else        Console.Write("No");}} // This code is contributed by 29AjayKumar
<script>     // JavaScript program to check if the word    // exists in the grid or not         let r = 4;    let c = 4;     // 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    function findmatch(mat, pat, x, y, nrow, ncol, level)    {        let 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            let temp = mat[x][y];            mat[x][y] = '#';             // finding subpattern in 4 directions            let 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    function checkMatch(mat, pat, nrow, ncol)    {         let l = pat.length;         // if total characters in matrix is        // less then pattern length        if (l > nrow * ncol)            return false;         // Traverse in the grid        for (let i = 0; i < nrow; i++)        {            for (let 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;    }         let grid = [ "axmy".split(''),                        "bgdf".split(''),                        "xeet".split(''),                        "raks".split('') ];       // Function to check if word exists or not    if (checkMatch(grid, "geeks", r, c))        document.write("Yes");    else        document.write("No"); </script>
Yes
 
YouTubeGeeksforGeeks500K subscribersCheck if a word exists in a grid or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 15:15•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=UDQ_FgNbArA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
ankthon
29AjayKumar
decode2207
akshitsaxenaa09
sagar0719kumar
Memoization
Microsoft
Dynamic Programming
Pattern Searching
Recursion
Microsoft
Dynamic Programming
Recursion
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Longest Palindromic Substring | Set 1
Subset Sum Problem | DP-25
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching