Given a 2-D grid of characters mat[][] and a string word, the task is to check if that word exist in the grid mat[][] 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: mat[][] = [['T', 'E', 'E'], ['S', 'G', 'K'], ['T', 'E', 'L']] word = "GEEK" Output: true Explanation: Word "GEEK" can be found in the given grid as follows
Input: mat[][] = [['T', 'E', 'U'], ['S', 'G', 'K'], ['T', 'E', 'L']] word = "GEEK" Output: false Explanation: Word "GEEK" cannot be found in the given grid.
Using Backtracking
The idea is to use backtracking to find a word in a grid by exploring different paths.
We traverse through the entire grid, and whenever we find the first letter of the word, we start a recursive search from that cell.
From the current matching cell, we check all four possible directions (down, right, up, left) to continue matching the remaining letters of the word.
As we explore each direction, we temporarily replace the value with another value the current cell to mark it as visited to avoid using this cell twice within the same path. After exploring a path, we backtrack by placing the original value at the cell, allowing it to be reused in other paths.
When all characters of the word were successfully matched, return true.
Note: When we go out of bounds or hit an unmatched character, we backtrack to previous matched cell and try another direction.
C++
// C++ program to check if the word exists in the grid or not#include<iostream>#include<vector>usingnamespacestd;// Function to check if a word exists in a grid// starting from the first match in the grid// wIdx: index till which pattern is matched// x, y: current position in 2D arrayboolfindMatch(vector<vector<char>>&mat,stringword,intx,inty,intwIdx){intwLen=word.length();intn=mat.size();intm=mat[0].size();// Pattern matchedif(wIdx==wLen)returntrue;// Out of Boundaryif(x<0||y<0||x>=n||y>=m)returnfalse;// If grid matches with a letter while// recursionif(mat[x][y]==word[wIdx]){// Marking this cell as visitedchartemp=mat[x][y];mat[x][y]='#';// finding subpattern in 4 directionsboolres=findMatch(mat,word,x-1,y,wIdx+1)||findMatch(mat,word,x+1,y,wIdx+1)||findMatch(mat,word,x,y-1,wIdx+1)||findMatch(mat,word,x,y+1,wIdx+1);// marking this cell as unvisited againmat[x][y]=temp;returnres;}// Not matching then return falsereturnfalse;}// Function to check if the word exists in the matrix or notboolisWordExist(vector<vector<char>>&mat,stringword){intwLen=word.length();intn=mat.size();intm=mat[0].size();// if total characters in matrix is// less than word lengthif(wLen>n*m)returnfalse;// Traverse in the gridfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// If first letter matches, then recur and checkif(mat[i][j]==word[0]){if(findMatch(mat,word,i,j,0))returntrue;}}}returnfalse;}intmain(){vector<vector<char>>mat={{'a','x','m','y'},{'b','g','d','f'},{'x','e','e','t'},{'r','a','k','s'}};stringword="geeks";cout<<(isWordExist(mat,word)?"true":"false");return0;}
Java
// Java program to check if the word exists in the grid or notimportjava.util.*;classGfG{// Function to check if a word exists in a grid// starting from the first match in the grid// wIdx: index till which pattern is matched// x, y: current position in 2D arraystaticbooleanfindMatch(char[][]mat,Stringword,intx,inty,intwIdx){intwLen=word.length();intn=mat.length;intm=mat[0].length;// Pattern matchedif(wIdx==wLen)returntrue;// Out of Boundaryif(x<0||y<0||x>=n||y>=m)returnfalse;// If grid matches with a letter while recursionif(mat[x][y]==word.charAt(wIdx)){// Marking this cell as visitedchartemp=mat[x][y];mat[x][y]='#';// finding subpattern in 4 directionsbooleanres=findMatch(mat,word,x-1,y,wIdx+1)||findMatch(mat,word,x+1,y,wIdx+1)||findMatch(mat,word,x,y-1,wIdx+1)||findMatch(mat,word,x,y+1,wIdx+1);// marking this cell as unvisited againmat[x][y]=temp;returnres;}// Not matching then return falsereturnfalse;}// Function to check if the word exists in the matrix or notstaticbooleanisWordExist(char[][]mat,Stringword){intwLen=word.length();intn=mat.length;intm=mat[0].length;// if total characters in matrix is less than word lengthif(wLen>n*m)returnfalse;// Traverse in the gridfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// If first letter matches, then recur and checkif(mat[i][j]==word.charAt(0)){if(findMatch(mat,word,i,j,0))returntrue;}}}returnfalse;}publicstaticvoidmain(String[]args){char[][]mat={{'a','x','m','y'},{'b','g','d','f'},{'x','e','e','t'},{'r','a','k','s'}};Stringword="geeks";System.out.println(isWordExist(mat,word));}}
Python
# Python program to check if the word exists in the grid or not# Function to check if a word exists in a grid# starting from the first match in the grid# wIdx: index till which pattern is matched# x, y: current position in 2D arraydeffindMatch(mat,word,x,y,wIdx):wLen=len(word)n=len(mat)m=len(mat[0])# Pattern matchedifwIdx==wLen:returnTrue# Out of Boundaryifx<0ory<0orx>=nory>=m:returnFalse# If grid matches with a letter while# recursionifmat[x][y]==word[wIdx]:# Marking this cell as visitedtemp=mat[x][y]mat[x][y]='#'# finding subpattern in 4 directionsres=(findMatch(mat,word,x-1,y,wIdx+1)orfindMatch(mat,word,x+1,y,wIdx+1)orfindMatch(mat,word,x,y-1,wIdx+1)orfindMatch(mat,word,x,y+1,wIdx+1))# marking this cell as unvisited againmat[x][y]=tempreturnres# Not matching then return falsereturnFalsedefisWordExist(mat,word):wLen=len(word)n=len(mat)m=len(mat[0])# if total characters in matrix is# less than word lengthifwLen>n*m:returnFalse# Traverse in the gridforiinrange(n):forjinrange(m):# If first letter matches, then recur and checkifmat[i][j]==word[0]:iffindMatch(mat,word,i,j,0):returnTruereturnFalseif__name__=="__main__":mat=[['a','x','m','y'],['b','g','d','f'],['x','e','e','t'],['r','a','k','s']]word="geeks"print("true"ifisWordExist(mat,word)else"false")
C#
// C# program to check if the word exists in the grid or notusingSystem;classGfG{// Function to check if a word exists in a grid// starting from the first match in the grid// wIdx: index till which pattern is matched// x, y: current position in 2D arraystaticboolfindMatch(char[,]mat,stringword,intx,inty,intwIdx){intwLen=word.Length;intn=mat.GetLength(0);intm=mat.GetLength(1);// Pattern matchedif(wIdx==wLen)returntrue;// Out of Boundaryif(x<0||y<0||x>=n||y>=m)returnfalse;// If grid matches with a letter while// recursionif(mat[x,y]==word[wIdx]){// Marking this cell as visitedchartemp=mat[x,y];mat[x,y]='#';// finding subpattern in 4 directionsboolres=findMatch(mat,word,x-1,y,wIdx+1)||findMatch(mat,word,x+1,y,wIdx+1)||findMatch(mat,word,x,y-1,wIdx+1)||findMatch(mat,word,x,y+1,wIdx+1);// marking this cell as unvisited againmat[x,y]=temp;returnres;}// Not matching then return falsereturnfalse;}// Function to check if the word exists in the matrix or notstaticboolisWordExist(char[,]mat,stringword){intwLen=word.Length;intn=mat.GetLength(0);intm=mat.GetLength(1);// if total characters in matrix is// less than word lengthif(wLen>n*m)returnfalse;// Traverse in the gridfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// If first letter matches, then recur and checkif(mat[i,j]==word[0]){if(findMatch(mat,word,i,j,0))returntrue;}}}returnfalse;}staticvoidMain(){char[,]mat={{'a','x','m','y'},{'b','g','d','f'},{'x','e','e','t'},{'r','a','k','s'}};stringword="geeks";Console.WriteLine(isWordExist(mat,word)?"true":"false");}}
JavaScript
// JavaScript program to check if the word exists in the grid or not// Function to check if a word exists in a grid// starting from the first match in the grid// wIdx: index till which pattern is matched// x, y: current position in 2D arrayfunctionfindMatch(mat,word,x,y,wIdx){constwLen=word.length;constn=mat.length;constm=mat[0].length;// Pattern matchedif(wIdx===wLen)returntrue;// Out of Boundaryif(x<0||y<0||x>=n||y>=m)returnfalse;// If grid matches with a letter while// recursionif(mat[x][y]===word[wIdx]){// Marking this cell as visitedconsttemp=mat[x][y];mat[x][y]='#';// finding subpattern in 4 directionsconstres=findMatch(mat,word,x-1,y,wIdx+1)||findMatch(mat,word,x+1,y,wIdx+1)||findMatch(mat,word,x,y-1,wIdx+1)||findMatch(mat,word,x,y+1,wIdx+1);// marking this cell as unvisited againmat[x][y]=temp;returnres;}// Not matching then return falsereturnfalse;}// Function to check if the word exists in the matrix or notfunctionisWordExist(mat,word){constwLen=word.length;constn=mat.length;constm=mat[0].length;// if total characters in matrix is// less than word lengthif(wLen>n*m)returnfalse;// Traverse in the gridfor(leti=0;i<n;i++){for(letj=0;j<m;j++){// If first letter matches, then recur and checkif(mat[i][j]===word[0]){if(findMatch(mat,word,i,j,0))returntrue;}}}returnfalse;}constmat=[['a','x','m','y'],['b','g','d','f'],['x','e','e','t'],['r','a','k','s']];constword="geeks";console.log(isWordExist(mat,word)?"true":"false");
Output
Yes
Time Complexity: O(n * m * 3wLen) , where n and m are number of rows and columns of 2-D character array mat[][], and wLen is length of string word.
In the backtracking function, we have four directions to explore. However, as we move forward, our choices decrease to three because we won't go back to the direction we just came from. We can visualize our recursive tree as a 3-ary tree with a height of wLen. Thus, the time complexity of the recursive function is O( 3wLen ).
This recursive function can be called n * m times in the worst case, so the total time complexity is O(n * m * 3wLen).
Auxiliary Space: O(wLen), which is the memory stack space used during recursion.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.