Word Boggle | Practice | GeeksforGeeks

Given a dictionary of distinct words and an M x N board where every cell has one character. Find all possible words from the dictionary that can be formed by a sequence of adjacent characters on the board. We can move to any of 8 adjacent characters
Note: While forming a word we can move to any of the 8 adjacent cells. A cell can be used only once in one word.

Example 1:
Input: 
N = 1
dictionary = {"CAT"}
R = 3, C = 3
board = {{C,A,P},{A,N,D},{T,I,E}}
Output:
CAT
Explanation: 
C A P
A N D
T I E
Words we got is denoted using same color.

Example 2:
Input:
N = 4
dictionary = {"GEEKS","FOR","QUIZ","GO"}
R = 3, C = 3 
board = {{G,I,Z},{U,E,K},{Q,S,E}}
Output:
GEEKS QUIZ
Explanation: 
G I Z
U E K
Q S E 
Words we got is denoted using same color.


Your task:
You don’t need to read input or print anything. Your task is to complete the function wordBoggle() which takes the dictionary contaning N space-separated strings and R*C board as input parameters and returns a list of words that exist on the board in lexicographical order.

Expected Time Complexity: O(N*W + R*C^2)
Expected Auxiliary Space: O(N*W + R*C)

Constraints:
1 ≤ N ≤ 15
1 ≤ R, C ≤ 50
1 ≤ length of Word ≤ 60
Each word can consist of both lowercase and uppercase letters.
0
neeshumaini5510 hours ago
class Solution:
    def wordBoggle(self,board,dictionary):
        """
        dic = [ g i z
                u e k
                q s e]
        word = Greeks quiz
        """
        
        res = []
        for i in range(len(dictionary)):
            word = dictionary[i]
            if self.find(board,word):
                res.append(word)
        return res
        
    def find(self,board,word):
        
        visited = [[False for i in range(len(board[0]))] for j in range(len(board))]
        def dfs(r,c,pos):
            if pos == len(word):
                return True
            if r >= 0 and c >= 0 and r < len(board) and c < len(board[0]) and visited[r][c] == False and board[r][c] == word[pos]:
                visited[r][c] = True
                if(dfs(r+1,c,pos+1) or dfs(r,c+1,pos+1) or dfs(r-1,c,pos+1) or dfs(r,c-1,pos+1) or dfs(r+1,c+1,pos+1) or dfs(r+1,c-1,pos+1) or dfs(r-1,c+1,pos+1) or dfs(r-1,c-1,pos+1)):
                    return True
                # to check that the character can be used in another word
                visited[r][c] = False
            
            return False
            
        indx = 0
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] == word[indx]:
                    if dfs(i,j,indx):
                        return True
        return False
0
sandeep55211 week ago
C++ DFS Solution by using Word Search
vector<pair<int,int>> p={{0,1},{1,0},{0,-1},{-1,0},{-1,-1},{1,1},{-1,1},{1,-1}};
   bool func(vector<vector<char>> &v,int i,int j,string &g,int k){
       if(k==g.size()) return true;
       if(i<0 or j<0 or i==v.size() or j==v[0].size() or v[i][j]!=g[k]) return false;
       char ch=v[i][j];
       v[i][j]='.';
       for(auto l:p) if(func(v,i+l.first,j+l.second,g,k+1)){
           v[i][j]=ch;
           return true;
       }
       v[i][j]=ch;
       return false;
   }
   bool isWordExist(vector<vector<char>>& v, string &g) {
       int m=v.size(),n=v[0].size();
       for(int i=0;i<m;i++){
           for(int j=0;j<n;j++) if(func(v,i,j,g,0)) return true;
       }
       return false;
   }
vector<string> wordBoggle(vector<vector<char> >& board, vector<string>& dic) {
    // Code here
    vector<string> ans;
    for(auto i: dic) if(isWordExist(board,i)) ans.push_back(i);
    return ans;
}
0
kuldeepy104592 weeks ago
int dx[8]={1,1,0,-1,-1,-1,0,1};     int dy[8]={0,1,1,1,0,-1,-1,-1};     bool dfs(vector<vector<char>>&board,string temp,vector<vector<bool>>&visited,int x,int y,int r,int c,int index){            if(x<0||x>=r||y<0||y>=c||visited[x][y]==true||temp[index]!=board[x][y]){                return false;            }            if(index==temp.length()-1){                return true;            }            if(index>=temp.length()){                return false;            }            visited[x][y]=true;            for(int i=0;i<8;i++){                int p=x+dx[i],q=y+dy[i];                bool result = dfs(board,temp,visited,p,q,r,c,index+1);                if(result){                    return true;                }            }            visited[x][y]=false;            return false;     }    bool search(vector<vector<char>>&board,string word,int r,int c){            vector<vector<bool>>visited (r,vector<bool>(c,false));            for(int i=0;i<r;i++){                for(int j=0;j<c;j++){                    if(board[i][j]==word[0]){                        if(dfs(board,word,visited,i,j,r,c,0)){                            return true;                        }                    }                }            }            return false;                }vector<string> wordBoggle(vector<vector<char> >& board, vector<string>& dictionary) {    // Code here    vector<string>ans;    int r= board.size(),c=board[0].size();    for(auto word:dictionary){        if(search(board,word,r,c)){            ans.push_back(word);        }    }    return ans;}
0
phenomenal13 weeks ago
JAVA Solution
class Solution
{
    boolean flag;
    public String[] wordBoggle(char board[][], String[] dictionary)
    {
        int m = board.length;
        int n = board[0].length;
        boolean check;
        Set<String> set = new TreeSet<>();
        boolean vis[][] = new boolean[m][n];
        
        for(String s:dictionary)
        {
            check=false;
            flag=false;
            for(int i=0;i<m;i++)
            {
                for(int j=0;j<n;j++)
                if(board[i][j]==s.charAt(0))
                {
                    
                    search(s,board,vis,i,j,1,1);
                    
                    if(flag)
                    {
                        check=true;
                        set.add(s);
                        break;
                    }
                }
                if(check)
                break;
            }
        }
        
        String res[] = new String[set.size()];
        int k=0;
        
        for(String s:set)
        res[k++]=s;
        
        return res;
    }
    
    void search(String word,char board[][],boolean vis[][],int i,int j,int count,int k)
    {
        if(k==word.length())
        {
            flag=true;
            return;
        }
        
        if((i-1)>=0 && (j-1)>=0 && !vis[i-1][j-1] && board[i-1][j-1]==word.charAt(k))
        {
            vis[i][j]=true;
            search(word,board,vis,i-1,j-1,count++,k+1);
            vis[i][j]=false;
        }
        if((i-1)>=0 && !vis[i-1][j] && board[i-1][j]==word.charAt(k))
        {
            vis[i][j]=true;
            search(word,board,vis,i-1,j,count++,k+1);
            vis[i][j]=false;
        }
        if((i-1)>=0 && (j+1)<board[0].length && !vis[i-1][j+1] && board[i-1][j+1]==word.charAt(k))
        {
            vis[i][j]=true;
            search(word,board,vis,i-1,j+1,count++,k+1);
            vis[i][j]=false;
        }
        if((j+1)<board[0].length && !vis[i][j+1] && board[i][j+1]==word.charAt(k))
        {
            vis[i][j]=true;
            search(word,board,vis,i,j+1,count++,k+1);
            vis[i][j]=false;
        }
        if((i+1)<board.length && (j+1)<board[0].length && !vis[i+1][j+1] && board[i+1][j+1]==word.charAt(k))
        {
            vis[i][j]=true;
            search(word,board,vis,i+1,j+1,count++,k+1);
            vis[i][j]=false;
        }
        if((i+1)<board.length && !vis[i+1][j] && board[i+1][j]==word.charAt(k))
        {
            vis[i][j]=true;
            search(word,board,vis,i+1,j,count++,k+1);
            vis[i][j]=false;
        }
        if((i+1)<board.length && (j-1)>=0 && !vis[i+1][j-1] && board[i+1][j-1]==word.charAt(k))
        {
            vis[i][j]=true;
            search(word,board,vis,i+1,j-1,count++,k+1);
            vis[i][j]=false;
        }
        if((j-1)>=0 && !vis[i][j-1] && board[i][j-1]==word.charAt(k))
        {
            vis[i][j]=true;
            search(word,board,vis,i,j-1,count++,k+1);
            vis[i][j]=false;
        }
        return;
    }
}
0
19bcs13143 weeks ago
class Solution
{
    public String[] wordBoggle(char board[][], String[] dictionary)
    {
        // Write your code here
        ArrayList<String>  l=new ArrayList<>();
        int r=board.length,c=board[0].length;
        for(String word:dictionary){
            if(search(board,word,r,c)){
                l.add(word);
            }
        }
        
        String[] ans=new String[l.size()];
        int i=0;
        for(String x:l){
            ans[i++]=x;
        }
        
        return ans;
        
    }
    
    public boolean  search(char[][] b,String word,int r,int c){
        boolean[][] visit=new boolean[r][c];
        for(int i=0;i<r;i++){
            for(int j=0;j<c;j++){
                if(b[i][j]==word.charAt(0)){
                    if(dfs(b,word,visit,i,j,r,c,0)){
                        return true;
                    }
                }
            }
        }
        
        return false;
    }
    
    
    int dx[] = {1, 1, 0, -1, -1, -1, 0, 1};
    int dy[] = {0, 1, 1, 1, 0, -1, -1, -1};

    public boolean dfs(char b[][],String temp,boolean[][] visit,int x,int y ,
    int r,int c,int index){
        
        if(x<0 || x>=r || y<0 || y>=c || visit[x][y]==true || temp.charAt(index)!=b[x][y]){
            return false;
        }
        
        if(index==temp.length()-1){
            return true;
        }
        if(index>=temp.length()){
            return false;
        }
        visit[x][y]=true;
        for(int i=0;i<8;i++){
            int p=x+dx[i],q=y+dy[i];
            
                boolean result=dfs(b,temp,visit,p,q,r,c,index+1);
                if(result==true){
                    return true;
                }
            
        }
        visit[x][y]=false;
        return false;
    }
}
0
joyrockok3 weeks ago
class Solution{   static public ArrayList<String> resultList;// = new ArrayList<String>();   static int Row, Col;   static int cnt=0;      public String[] wordBoggle(char board[][], String[] dic)   {
       // Write your code here       Row = board.length;       Col = board[0].length;              resultList = new ArrayList<String>();              boolean [][]visited = new boolean[Row][Col];              String str = "";              boolean rslt = false;       for(String word : dic) {        rslt = false;                for(int i=0; i<Row; i++) {            for(int j=0; j<Col; j++) {                rslt = findWord(visited, board, word, i, j, str);                                if(rslt) {                  break;                }            }            if(rslt) {              break;            }        }       }              String [] result = new String[resultList.size()];       for(int i=0; i<resultList.size(); i++) {        result[i] = resultList.get(i);       }              return result;   }      static boolean findWord(boolean visited[][], char board[][], String word, int i, int j, String str) {              visited[i][j] = true;       str = str + board[i][j];              if(str.length() <= word.length()) {        if(str.equals(word.substring(0, str.length())) == false) {         visited[i][j] = false;         return false;        }       }              if(isOneOfDic(word, str)) {         resultList.add(str);                  visited[i][j] = false;        return true;       }               boolean rslt = false;       for(int row = i-1; row <= i+1 && row < Row; row++ ) {           for(int col = j-1; col <= j+1 && col < Col; col++) {               if(row >=0 && col >= 0 && !visited[row][col]) {                   rslt = findWord(visited, board, word, row, col, str);                                      if(rslt) {                    visited[i][j] = false;                    return rslt;                   }               }           }       }          visited[i][j] = false;              return false;   }      static boolean isOneOfDic(String word, String str) {        if(word.equals(str) && resultList.contains(word) == false) {     return true;    }        return false;             }}
0
hamidnourashraf4 weeks ago
class Solution:
    def rec_wb(self, board, i, j, M, N, word, start, visited):
        if start >= len(word):
            return True
        
        if i < 0 or i >= M or j < 0 or j >= N:
            return False
        
        if visited[i][j] == 0:
            return False
            
        if board[i][j] == word[start]:
            visited[i][j] = 0
            up = self.rec_wb(board, i-1, j, M, N, word, start+1, visited)
            down = self.rec_wb(board, i+1, j, M, N, word, start+1, visited)
            right = self.rec_wb(board, i, j+1, M, N, word, start+1, visited)
            left = self.rec_wb(board, i, j-1, M, N, word, start+1, visited)
            nw = self.rec_wb(board, i-1, j-1, M, N, word, start+1, visited)
            ne = self.rec_wb(board, i-1, j+1, M, N, word, start+1, visited)
            sw = self.rec_wb(board, i+1, j-1, M, N, word, start+1, visited)
            ss = self.rec_wb(board, i+1, j+1, M, N, word, start+1, visited)
            visited[i][j] = -1
            return (up or down or right or left or nw or ne or sw or ss)
        else:
            return False
        
    def wordBoggle(self, board, dictionary):
        M = len(board)
        N = len(board[0])
        idx_dict = dict()
        for i in range(M):
            for j in range(N):
                if board[i][j] in idx_dict:
                    idx_dict[board[i][j]].append((i, j))
                else:
                    idx_dict[board[i][j]] = [(i, j)]
        res = []
        for word in dictionary:
            if word[0] in idx_dict:
                for idx in idx_dict[word[0]]:
                    visited = [[-1]*N for i in range(M)]
                    if self.rec_wb(board, idx[0], idx[1], M, N, word, 0, visited):
                        res.append(word)
                        break
        return res
0
adityapratapsingh0820171 month ago
class Solution:
    def wordBoggle(self,board,dictionary):
        # return list of words(str) found in the board
        res=[]
        for i in range(len(dictionary)):
            word=dictionary[i]
            if exist(board,word):
                res.append(word)
        return res
def exist(board,word):
    r=len(board)
    c=len(board[0])
    visited=[[False for i in range(c)]for j in range(r)]
    idx=0
    for i in range(r):
        for j in range(c):
            if board[i][j]==word[idx]:
                if dfs(board,visited,i,j,word,idx):
                    return True
    return False
def dfs(board,visited,i,j,word,idx):
    
    if idx==len(word):
        return True
    if i>=0 and i <len(board) and j>=0 and j<len(board[0]) and visited[i][j]==False and board[i][j]==word[idx]:
        visited[i][j]=True
        if (dfs(board,visited,i-1,j-1,word,idx+1) or
        dfs(board,visited,i-1,j,word,idx+1) or
        dfs(board,visited,i-1,j+1,word,idx+1) or
        dfs(board,visited,i,j-1,word,idx+1) or
        dfs(board,visited,i,j+1,word,idx+1) or
        dfs(board,visited,i+1,j-1,word,idx+1) or
        dfs(board,visited,i+1,j+1,word,idx+1) or
        dfs(board,visited,i+1,j,word,idx+1)):
            return True
        visited[i][j]=False
    return False
+1
madhukartemba2 months ago
JAVA SOLUTION USING DFS:
class Solution
{
    static int dx[] = {1, 1, 0, -1, -1, -1, 0, 1};
    static int dy[] = {0, 1, 1, 1, 0, -1, -1, -1};
    
    private boolean dfs(int ind, int x, int y, char board[][], boolean visited[][], String word, int n, int m)
    {
        if(ind==word.length()) return true;
        
        if(x<0 || y<0 || x>=n || y>=m || visited[x][y]==true || board[x][y] != word.charAt(ind)) return false;
        
        visited[x][y] = true;
        
        for(int i=0; i<8; i++)
        {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(dfs(ind+1, nx, ny, board, visited, word, n, m)) return true;
        }
        
        visited[x][y] = false;
        
        return false;
        
    }
    
    private boolean searchWord(char board[][], String word, int n, int m)
    {
        boolean visited[][] = new boolean[n][m];
        
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                if(board[i][j]==word.charAt(0))
                {
                    if(dfs(0, i, j, board, visited, word, n, m))
                    {
                        return true;
                    }
                }
            }
        }
        
        return false;
    }
    
    public String[] wordBoggle(char board[][], String[] dictionary)
    {
        
        int n = board.length;
        int m = board[0].length;
        
        ArrayList<String> ans = new ArrayList<>();
        
        for(String word : dictionary)
        {
            if(searchWord(board, word, n, m)) ans.add(word);
        }
        
        String res[] = new String[ans.size()];
        
        int n_words = ans.size();
        
        for(int i=0; i<n_words; i++)
        {
            res[i] = ans.get(i);
        }
        
        return res;
        
        
    }
}
0
code4me18
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.