Given a 2D grid m*n of characters and a word, the task is to find all occurrences of the given word in the grid. A word can be matched in all 8 directions at any point. Word is said to be found in a direction if all characters match in this direction (not in zig-zag form). The 8 directions are, Horizontally Left, Horizontally Right, Vertically Up, Vertically Down and 4 Diagonal directions.
Note: The returning list should be lexicographically smallest. If the word can be found in multiple directions starting from the same coordinates, the list should contain the coordinates only once.
[Naive Approach] Using Recursion - O(m*n*k) Time and O(k) Space
Visit each cell in the grid and check in all eight directions (up, down, left, right, and diagonals) to find the word. And for each cell, we try to move in one direction.
We keep checking, if the letter in the cell of grid matches the word as we move in the chosen direction.
If we find the whole word, we store the starting point.
We do this for every cell in the grid recursively.
C++
// C++ program to search a word in a 2D grid#include<bits/stdc++.h>usingnamespacestd;// This function checks if the given // coordinate is validboolvalidCoord(intx,inty,intm,intn){if(x>=0&&x<m&&y>=0&&y<n)returntrue;returnfalse;}// This function searches for the given word// in a given direction from the coordinate.boolfindWord(intindex,stringword,vector<vector<char>>&grid,intx,inty,intdirX,intdirY){// if word has been foundif(index==word.length())returntrue;// if the current coordinate is // valid and characters match, then// check the next indexif(validCoord(x,y,grid.size(),grid[0].size())&&word[index]==grid[x][y])returnfindWord(index+1,word,grid,x+dirX,y+dirY,dirX,dirY);returnfalse;}// This function calls search2D for each coordinatevector<vector<int>>searchWord(vector<vector<char>>grid,stringword){intm=grid.size();intn=grid[0].size();vector<vector<int>>ans;// x and y are used to set the direction in which// word needs to be searched.vector<int>x={-1,-1,-1,0,0,1,1,1};vector<int>y={-1,0,1,-1,1,-1,0,1};for(inti=0;i<m;i++){for(intj=0;j<n;j++){// Search in all 8 directionsfor(intk=0;k<8;k++){// If word is found, then append the // coordinates into answer and break.if(findWord(0,word,grid,i,j,x[k],y[k])){ans.push_back({i,j});break;}}}}returnans;}voidprintResult(vector<vector<int>>ans){for(inti=0;i<ans.size();i++){cout<<"{"<<ans[i][0]<<","<<ans[i][1]<<"}"<<" ";}cout<<endl;}intmain(){vector<vector<char>>grid={{'a','b','a','b'},{'a','b','e','b'},{'e','b','e','b'}};stringword="abe";vector<vector<int>>ans=searchWord(grid,word);printResult(ans);}
Java
// Java program to search a word in a 2D gridimportjava.util.*;classGfG{// This function checks if the given// coordinate is validstaticbooleanvalidCoord(intx,inty,intm,intn){if(x>=0&&x<m&&y>=0&&y<n)returntrue;returnfalse;}// This function searches for the given word// in a given direction from the coordinate.staticbooleanfindWord(intindex,Stringword,char[][]grid,intx,inty,intdirX,intdirY){// if word has been foundif(index==word.length())returntrue;// if the current coordinate is// valid and characters match, then// check the next indexif(validCoord(x,y,grid.length,grid[0].length)&&word.charAt(index)==grid[x][y])returnfindWord(index+1,word,grid,x+dirX,y+dirY,dirX,dirY);returnfalse;}// This function calls search2D for each coordinatestaticint[][]searchWord(char[][]grid,Stringword){intm=grid.length;intn=grid[0].length;List<int[]>ans=newArrayList<>();// x and y are used to set the direction in which// word needs to be searched.int[]x={-1,-1,-1,0,0,1,1,1};int[]y={-1,0,1,-1,1,-1,0,1};for(inti=0;i<m;i++){for(intj=0;j<n;j++){// Search in all 8 directionsfor(intk=0;k<8;k++){// If word is found, then append the// coordinates into answer and break.if(findWord(0,word,grid,i,j,x[k],y[k])){ans.add(newint[]{i,j});break;}}}}returnans.toArray(newint[0][]);}staticvoidprintResult(int[][]ans){for(int[]a:ans){System.out.print("{"+a[0]+","+a[1]+"}"+" ");}System.out.println();}publicstaticvoidmain(String[]args){char[][]grid={{'a','b','a','b'},{'a','b','e','b'},{'e','b','e','b'}};Stringword="abe";int[][]ans=searchWord(grid,word);printResult(ans);}}
Python
# Python program to search a word in a 2D grid# This function checks if the given# coordinate is validdefisValid(x,y,sizeX,sizeY):return0<=x<sizeXand0<=y<sizeYdeffindWordInDirection(grid,n,m,word,index,x,y,dirX,dirY):ifindex==len(word):returnTrueifisValid(x,y,n,m)andword[index]==grid[x][y]:returnfindWordInDirection(grid,n,m,word,index+1,x+dirX,y+dirY,dirX,dirY)returnFalsedefsearchWord(grid,word):ans=[]n=len(grid)m=len(grid[0])# Directions for 8 possible movementsdirections=[(1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)]foriinrange(n):forjinrange(m):# Check if the first character matchesifgrid[i][j]==word[0]:fordirX,dirYindirections:iffindWordInDirection(grid,n,m,word,0,i,j,dirX,dirY):ans.append([i,j])breakreturnansdefprintResult(ans):forainans:print(f"{{{a[0]},{a[1]}}}",end=" ")print()if__name__=="__main__":grid=[['a','b','a','b'],['a','b','e','b'],['e','b','e','b']]word="abe"ans=searchWord(grid,word)printResult(ans)
C#
// C# program to search a word in a 2D gridusingSystem;usingSystem.Collections.Generic;classGfG{// This function checks if the given// coordinate is validstaticboolvalidCoord(intx,inty,intm,intn){if(x>=0&&x<m&&y>=0&&y<n)returntrue;returnfalse;}// This function searches for the given word// in a given direction from the coordinate.staticboolfindWord(intindex,stringword,char[,]grid,intx,inty,intdirX,intdirY){// if word has been foundif(index==word.Length)returntrue;// if the current coordinate is// valid and characters match, then// check the next indexif(validCoord(x,y,grid.GetLength(0),grid.GetLength(1))&&word[index]==grid[x,y])returnfindWord(index+1,word,grid,x+dirX,y+dirY,dirX,dirY);returnfalse;}// This function calls search2D for each coordinatestaticint[][]searchWord(char[,]grid,stringword){intm=grid.GetLength(0);intn=grid.GetLength(1);List<int[]>ans=newList<int[]>();// x and y are used to set the direction in which// word needs to be searched.int[]x={-1,-1,-1,0,0,1,1,1};int[]y={-1,0,1,-1,1,-1,0,1};for(inti=0;i<m;i++){for(intj=0;j<n;j++){// Search in all 8 directionsfor(intk=0;k<8;k++){// If word is found, then append the// coordinates into answer and break.if(findWord(0,word,grid,i,j,x[k],y[k])){ans.Add(newint[]{i,j});break;}}}}returnans.ToArray();}staticvoidprintResult(int[][]ans){foreach(varainans){Console.Write("{"+a[0]+","+a[1]+"}"+" ");}Console.WriteLine();}staticvoidMain(){char[,]grid={{'a','b','a','b'},{'a','b','e','b'},{'e','b','e','b'}};stringword="abe";int[][]ans=searchWord(grid,word);printResult(ans);}}
JavaScript
// JavaScript program to search a word in a 2D grid// This function checks if the given // coordinate is validfunctionvalidCoord(x,y,m,n){return(x>=0&&x<m&&y>=0&&y<n);}// This function searches for the given word// in a given direction from the coordinate.functionfindWord(index,word,grid,x,y,dirX,dirY){// if word has been foundif(index===word.length)returntrue;// if the current coordinate is // valid and characters match, then// check the next indexif(validCoord(x,y,grid.length,grid[0].length)&&word[index]===grid[x][y])returnfindWord(index+1,word,grid,x+dirX,y+dirY,dirX,dirY);returnfalse;}// This function calls search2D for each coordinatefunctionsearchWord(grid,word){letm=grid.length;letn=grid[0].length;letans=[];// x and y are used to set the direction in which// word needs to be searched.letx=[-1,-1,-1,0,0,1,1,1];lety=[-1,0,1,-1,1,-1,0,1];for(leti=0;i<m;i++){for(letj=0;j<n;j++){// Search in all 8 directionsfor(letk=0;k<8;k++){// If word is found, then append the // coordinates into answer and break.if(findWord(0,word,grid,i,j,x[k],y[k])){ans.push([i,j]);break;}}}}returnans;}functionprintResult(ans){for(leti=0;i<ans.length;i++){console.log("{"+ans[i][0]+","+ans[i][1]+"}");}}constgrid=[['a','b','a','b'],['a','b','e','b'],['e','b','e','b']];constword="abe";constans=searchWord(grid,word);printResult(ans);
Output
{0,0} {0,2} {1,0}
Time Complexity: O(m*n*k), where m is the number of rows, n is the number of columns and k is the length of word. Auxiliary Space: O(k), recursion stack space.
[Expected Approach] Using Iteration - O(m*n*k) Time and O(1) Space
This is iterative approach for the above discussed recursive approach. Here, for each cell, we try to move in one direction iteratively.
We keep checking, if the letter in the cell of grid matches the word as we move in the chosen direction.
If we find the whole word, we store the starting point.
We do this for every cell in the grid.
C++
// C++ program to search a word in a 2D grid#include<bits/stdc++.h>usingnamespacestd;// This function searches for the given word// in all 8 directions from the coordinate.boolsearch2D(vector<vector<char>>grid,introw,intcol,stringword){intm=grid.size();intn=grid[0].size();// return false if the given coordinate// does not match with first index char.if(grid[row][col]!=word[0])returnfalse;intlen=word.size();// x and y are used to set the direction in which// word needs to be searched.vector<int>x={-1,-1,-1,0,0,1,1,1};vector<int>y={-1,0,1,-1,1,-1,0,1};// This loop will search in all the 8 directions// one by one. It will return true if one of the // directions contain the word.for(intdir=0;dir<8;dir++){// Initialize starting point for current directionintk,currX=row+x[dir],currY=col+y[dir];// First character is already checked, match remaining// charactersfor(k=1;k<len;k++){// break if out of boundsif(currX>=m||currX<0||currY>=n||currY<0)break;if(grid[currX][currY]!=word[k])break;// Moving in particular directioncurrX+=x[dir],currY+=y[dir];}// If all character matched, then value of must// be equal to length of wordif(k==len)returntrue;}// if word is not found in any direction,// then return falsereturnfalse;}// This function calls search2D for each coordinatevector<vector<int>>searchWord(vector<vector<char>>grid,stringword){intm=grid.size();intn=grid[0].size();vector<vector<int>>ans;for(inti=0;i<m;i++){for(intj=0;j<n;j++){// if the word is found from this coordinate,// then append it to result.if(search2D(grid,i,j,word)){ans.push_back({i,j});}}}returnans;}voidprintResult(vector<vector<int>>ans){for(inti=0;i<ans.size();i++){cout<<"{"<<ans[i][0]<<","<<ans[i][1]<<"}"<<" ";}cout<<endl;}intmain(){vector<vector<char>>grid={{'a','b','a','b'},{'a','b','e','b'},{'e','b','e','b'}};stringword="abe";vector<vector<int>>ans=searchWord(grid,word);printResult(ans);}
Java
// Java program to search word in 2D// grid in 8 directionsimportjava.util.*;classGfG{// This function searches for the given word// in all 8 directions from the coordinate.staticbooleansearch2D(char[][]grid,introw,intcol,Stringword){intm=grid.length;intn=grid[0].length;// return false if the given coordinate// does not match with first index char.if(grid[row][col]!=word.charAt(0))returnfalse;intlen=word.length();// x and y are used to set the direction in which// word needs to be searched.int[]x={-1,-1,-1,0,0,1,1,1};int[]y={-1,0,1,-1,1,-1,0,1};// This loop will search in all the 8 directionsfor(intdir=0;dir<8;dir++){intk,currX=row+x[dir],currY=col+y[dir];// First character is already checked, match// remainingfor(k=1;k<len;k++){if(currX>=m||currX<0||currY>=n||currY<0)break;if(grid[currX][currY]!=word.charAt(k))break;currX+=x[dir];currY+=y[dir];}if(k==len)returntrue;}returnfalse;}// This function calls search2D for each coordinatestaticint[][]searchWord(char[][]grid,Stringword){intm=grid.length;intn=grid[0].length;// Max possible occurrencesint[][]ans=newint[m*n][2];intcount=0;for(inti=0;i<m;i++){for(intj=0;j<n;j++){if(search2D(grid,i,j,word)){ans[count][0]=i;ans[count][1]=j;count++;}}}// Resize the array to fit the actual number of// found coordinatesint[][]result=newint[count][2];for(inti=0;i<count;i++){result[i]=ans[i];}returnresult;}staticvoidprintResult(int[][]ans){for(int[]coords:ans){System.out.print("{"+coords[0]+","+coords[1]+"}"+" ");}System.out.println();}publicstaticvoidmain(String[]args){char[][]grid={{'a','b','a','b'},{'a','b','e','b'},{'e','b','e','b'}};Stringword="abe";int[][]ans=searchWord(grid,word);printResult(ans);}}
Python
# Python program to search word in 2D grid in 8 directions# This function searches for the given word# in all 8 directions from the coordinate.defsearch2D(grid,row,col,word):m=len(grid)n=len(grid[0])# return false if the given coordinate# does not match with first index char.ifgrid[row][col]!=word[0]:returnFalselenWord=len(word)# x and y are used to set the direction in which# word needs to be searched.x=[-1,-1,-1,0,0,1,1,1]y=[-1,0,1,-1,1,-1,0,1]# This loop will search in all the 8 directions# one by one. It will return true if one of the# directions contain the word.fordirinrange(8):# Initialize starting point for current directioncurrX,currY=row+x[dir],col+y[dir]k=1whilek<lenWord:# break if out of boundsifcurrX>=morcurrX<0orcurrY>=norcurrY<0:break# break if characters dont matchifgrid[currX][currY]!=word[k]:break# Moving in particular directioncurrX+=x[dir]currY+=y[dir]k+=1# If all character matched, then value of must# be equal to length of wordifk==lenWord:returnTrue# if word is not found in any direction,# then return falsereturnFalse# This function calls search2D for each coordinatedefsearchWord(grid,word):m=len(grid)n=len(grid[0])ans=[]foriinrange(m):forjinrange(n):# if the word is found from this coordinate,# then append it to result.ifsearch2D(grid,i,j,word):ans.append((i,j))returnansdefprintResult(ans):forcoordinans:print(f"{{{coord[0]},{coord[1]}}}",end=" ")print()if__name__=="__main__":grid=[['a','b','a','b'],['a','b','e','b'],['e','b','e','b']]word="abe"ans=searchWord(grid,word)printResult(ans)
C#
// C# program to search word in 2D grid in 8 directionsusingSystem;usingSystem.Collections.Generic;classGfG{// This function searches for the given word// in all 8 directions from the coordinate.staticboolsearch2D(char[][]grid,introw,intcol,stringword){intm=grid.Length;intn=grid[0].Length;// return false if the given coordinate// does not match with first index char.if(grid[row][col]!=word[0])returnfalse;intlen=word.Length;// x and y are used to set the direction in which// word needs to be searched.int[]x={-1,-1,-1,0,0,1,1,1};int[]y={-1,0,1,-1,1,-1,0,1};// This loop will search in all the 8 directions// one by one. It will return true if one of the // directions contain the word.for(intdir=0;dir<8;dir++){// Initialize starting point for current directionintk,currX=row+x[dir],currY=col+y[dir];// First character is already checked, match remaining// charactersfor(k=1;k<len;k++){// break if out of boundsif(currX>=m||currX<0||currY>=n||currY<0)break;// break if characters dont matchif(grid[currX][currY]!=word[k])break;// Moving in particular directioncurrX+=x[dir];currY+=y[dir];}// If all character matched, then value of must// be equal to length of wordif(k==len)returntrue;}// if word is not found in any direction,// then return falsereturnfalse;}// This function calls search2D for each coordinatestaticList<int[]>searchWord(char[][]grid,stringword){intm=grid.Length;intn=grid[0].Length;List<int[]>ans=newList<int[]>();// if the word is found from this coordinate,// then append it to result.for(inti=0;i<m;i++){for(intj=0;j<n;j++){if(search2D(grid,i,j,word)){ans.Add(newint[]{i,j});}}}returnans;}staticvoidprintResult(List<int[]>ans){foreach(varcoordinans){Console.Write("{"+coord[0]+","+coord[1]+"}"+" ");}Console.WriteLine();}staticvoidMain(){char[][]grid=newchar[][]{newchar[]{'a','b','a','b'},newchar[]{'a','b','e','b'},newchar[]{'e','b','e','b'}};stringword="abe";List<int[]>ans=searchWord(grid,word);printResult(ans);}}
JavaScript
// JavaScript program to search word in 2D grid in 8 directions// This function searches for the given word// in all 8 directions from the coordinate.functionsearch2D(grid,row,col,word){letm=grid.length;letn=grid[0].length;// return false if the given coordinate// does not match with first index char.if(grid[row][col]!==word[0])returnfalse;letlen=word.length;// x and y are used to set the direction in which// word needs to be searched.letx=[-1,-1,-1,0,0,1,1,1];lety=[-1,0,1,-1,1,-1,0,1];// This loop will search in all the 8 directions// one by one. It will return true if one of the // directions contain the word.for(letdir=0;dir<8;dir++){// Initialize starting point for current directionletcurrX=row+x[dir],currY=col+y[dir],k=1;// First character is already checked, match remaining// charactersfor(k=1;k<len;k++){// break if out of boundsif(currX>=m||currX<0||currY>=n||currY<0)break;// break if characters dont matchif(grid[currX][currY]!==word[k])break;// Moving in particular directioncurrX+=x[dir];currY+=y[dir];}// If all character matched, then value of must// be equal to length of wordif(k===len)returntrue;}// if word is not found in any direction,// then return falsereturnfalse;}// This function calls search2D for each coordinatefunctionsearchWord(grid,word){letm=grid.length;letn=grid[0].length;letans=[];for(leti=0;i<m;i++){for(letj=0;j<n;j++){// if the word is found from this coordinate,// then append it to result.if(search2D(grid,i,j,word)){ans.push([i,j]);}}}returnans;}functionprintResult(ans){ans.forEach(coord=>{console.log("{"+coord[0]+","+coord[1]+"}");;});}letgrid=[['a','b','a','b'],['a','b','e','b'],['e','b','e','b']];letword="abe";letans=searchWord(grid,word);printResult(ans);
Output
{0,0} {0,2} {1,0}
Time complexity: O(m*n*k), where m is the number of rows, n is the number of columns and k is the length of word. Auxiliary Space: O(1).
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.