×

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in the dictionary or not. We have to return the words which are present in the dictionary.

 Input:  dictionary[] = {"JAVA", "PYTHON", "HERO", "GO"}

       boggle[][]   = { { 'H', 'I', 'O' },

                                { 'A', 'E', 'R' },

                                { 'J', 'V', 'A' } };

   isWord(str): returns true if str is present in dictionary

                   else false.

Output:        Following words of dictionary are present

                          HERO

                          JAVA

Concept behind the solution

 Here, we will use the concept of depth first traversal. We will check if a character can be a starting of a word in dictionary or not. In this way, every character will be traversed. The time complexity of this algorithm is O(n^2*m^2). Here n and m is row and column size of matrix.

Code:

// C++ program to find words in dictionary from board of characters

#include <cstring>
#include <iostream>
using namespace std;


#define M 3
#define N 3
string dictionary[] = { “HERO”, “JAVA”, “PYTHON”, "GO" };
int n = sizeof(dictionary) / sizeof(dictionary[0]);
bool isWord(string& str)
{
	for (int i = 0; i < n; i++)
		if (str.compare(dictionary[i]) == 0)
			return true;
	return false;
}
void findWordsUtil(char boggle[M][N], bool visited[M][N], int i,
				int j, string& str)
{
	visited[i][j] = true;
	str = str + boggle[i][j];
	if (isWord(str))
		cout << str << endl;
	for (int row = i - 1; row <= i + 1 && row < M; row++)
		for (int col = j - 1; col <= j + 1 && col < N; col++)
			if (row >= 0 && col >= 0 && !visited[row][col])
				findWordsUtil(boggle, visited, row, col, str);
	str.erase(str.length() - 1);
	visited[i][j] = false;
}
void findWords(char boggle[M][N])
{
	bool visited[M][N] = { { false } };
	string str = "";
	for (int i = 0; i < M; i++)
		for (int j = 0; j < N; j++)
			findWordsUtil(boggle, visited, i, j, str);
}
int main()
{
	char boggle[M][N] = { { ‘H’, ‘I’, ‘O’ },
						{ ‘A’, ‘E’, ‘R’ },
						{ ‘J’, ‘V’, ‘A’ } };


	cout << "Following words of dictionary are present\n";
	findWords(boggle);
	return 0;
}

// JAVA program to find words in dictionary from board of characters

class bn {
	static final String dictionary[] = { “HERO”, “JAVA”, “PYTHON”, "GUQ", "EE" };
	static final int n = dictionary.length;
	static final int M = 3, N = 3;
	static boolean isWord(String str)
	{
		for (int i = 0; i < n; i++)
			if (str.equals(dictionary[i]))
				return true;
		return false;
	}
	static void findWordsUtil(char boggle[][], boolean visited[][], int i,
							int j, String str)
	{
		visited[i][j] = true;
		str = str + boggle[i][j];
		if (isWord(str))
			System.out.println(str);
		for (int row = i - 1; row <= i + 1 && row < M; row++)
			for (int col = j - 1; col <= j + 1 && col < N; col++)
				if (row >= 0 && col >= 0 && !visited[row][col])
					findWordsUtil(boggle, visited, row, col, str);
		str = "" + str.charAt(str.length() - 1);
		visited[i][j] = false;
	}
	static void findWords(char boggle[][])
	{
		boolean visited[][] = new boolean[M][N];
		String str = "";
		for (int i = 0; i < M; i++)
			for (int j = 0; j < N; j++)
				findWordsUtil(boggle, visited, i, j, str);
	}
	public static void main(String args[])
	{
		char boggle[][] = { { ‘H’, ‘I’, ‘O’ },
							{ ‘A’, ‘E’, ‘R’ },
							{ ‘J’, ‘V’, ‘A’ } };


		System.out.println("Following words of dictionary are present");
		findWords(boggle);
	}
}

# Python program to find words in dictionary from board of characters

dictionary = [“HERO”, “JAVA”, “PYTHON”, "GO"]
n = len(dictionary)
M = 3
N = 3
def isWord(Str):
	for i in range(n):
		if (Str == dictionary[i]):
			return True
	return False
def findWordsUtil(boggle, visited, i, j, Str):
	visited[i][j] = True
	Str = Str + boggle[i][j]
	
	if (isWord(Str)):
		print(Str)
	
	row = i - 1
	while row <= i + 1 and row < M:
		col = j - 1
		while col <= j + 1 and col < N:
			if (row >= 0 and col >= 0 and not visited[row][col]):
				findWordsUtil(boggle, visited, row, col, Str)
			col+=1
		row+=1
	
	Str = "" + Str[-1]
	visited[i][j] = False
def findWords(boggle):
	visited = [[False for i in range(N)] for j in range(M)]
	
	Str = ""
	for i in range(M):
	for j in range(N):
		findWordsUtil(boggle, visited, i, j, Str)
boggle = [["G", "I", "Z"], ["U", "E", "K"], ["Q", "S", "E"]]


print("Following words of", "dictionary are present")
findWords(boggle)

// C# program to find words in dictionary from board of characters

using System;
using System.Collections.Generic;
class bn
{
	static readonly String []dictionary = { “HERO”, “JAVA”,
											“PYTHON”, "GUQ", "EE" };
	static readonly int n = dictionary.Length;
	static readonly int M = 3, N = 3;
	static bool isWord(String str)
	{
		for (int i = 0; i < n; i++)
			if (str.Equals(dictionary[i]))
				return true;
		return false;
	}
	static void findWordsUtil(char [,]boggle, bool [,]visited,
							int i, int j, String str)
	{
		visited[i, j] = true;
		str = str + boggle[i, j];
		if (isWord(str))
			Console.WriteLine(str);
		for (int row = i - 1; row <= i + 1 && row < M; row++)
			for (int col = j - 1; col <= j + 1 && col < N; col++)
				if (row >= 0 && col >= 0 && !visited[row, col])
					findWordsUtil(boggle, visited, row, col, str);
		str = "" + str[str.Length - 1];
		visited[i, j] = false;
	}
	static void findWords(char [,]boggle)
	{
		bool [,]visited = new bool[M, N];
		String str = "";
		for (int i = 0; i < M; i++)
			for (int j = 0; j < N; j++)
				findWordsUtil(boggle, visited, i, j, str);
	}
	public static void Main(String []args)
	{
		char [,]boggle = { { ‘H’, ‘I’, ‘O’ },
						{ ‘A’, ‘E’, ‘R’ },
						{ ‘J’, ‘V’, ‘A’ } };


		Console.WriteLine("Following words of " +
						"dictionary are present");
		findWords(boggle);
	}
}

// JavaScript program to find words in dictionary from board of characters

<script>
	var dictionary = [“HERO”, “JAVA”, “PYTHON”, "GO"];
	var n = dictionary.length;
	var M = 3,
		N = 3;
	
	function isWord(str)
	{
	
				for (var i = 0; i < n; i++) if (str == dictionary[i]) return true;
		return false;
	}
	function findWordsUtil(boggle, visited, i, j, str)
	{
	
		visited[i][j] = true;
		str = str + boggle[i][j];
		if (isWord(str)) document.write(str + "<br>");
		for (var row = i - 1; row <= i + 1 && row < M; row++)
		for (var col = j - 1; col <= j + 1 && col < N; col++)
			if (row >= 0 && col >= 0 && !visited[row][col])
			findWordsUtil(boggle, visited, row, col, str);
		str = "" + str[str.length - 1];
		visited[i][j] = false;
	}
	function findWords(boggle)
	{
	
		var visited = Array.from(Array(M), () => new Array(N).fill(0));
		var str = "";
		for (var i = 0; i < M; i++)
		for (var j = 0; j < N; j++) findWordsUtil(boggle, visited, i, j, str);
	}
	var boggle = [
		["G", "I", "Z"],
		["U", "E", "K"],
		["Q", "S", "E"],
	];


	document.write("Following words of " + "dictionary are present <br>");
	findWords(boggle);
	
	</script>

Output:

Boggle (Find all possible words from a board of characters)

Related Topics

Introduction and Implementation of Bloom Filter

It often happens with many of us that when we create an account on some applications like Github, it shows us that the username already exists. You can add some...

4 minutes read.

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

Implementation of stack

Implementation of stack: The stack can be implemented in two ways: using array and using a linked list. The pop and push operations in the array are simpler than the...

3 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.

What is B tree?

What do you mean by B Tree in Data Structures? In the technological world, a B tree is simply a well-managed and coordinated tree and an integral part of the data...

6 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

3 minutes read.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Union and Intersection of two Linked Lists

Union and Intersection of two Linked Lists This article explains how we can do the union and intersection of two linked lists. In this problem, we have given two linked lists...

3 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

Hash Table vs STL Map

Hash table and STL map are extremely valuable information structures in software engineering. Here we will consider the examination between their properties to be well as execution.  To start with, we will...

7 minutes read.

Asynchronous advantage actor-critic (A3C) Algorithm

The Asynchronous advantage actor-critic (A3C) Algorithm is one of the latest algorithms developed by the Artificial Intelligence division, Deep Mind at Google. It is used for the Deep Reinforcement Learning...

3 minutes read.

Bubble Sort vs Merge Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Merge Sort. In starting, we will first discuss the idea of sorting an array using bubble...

7 minutes read.

Lowest common ancestor in a binary search tree

Suppose you have given two values of nodes in a binary search tree. You have to find out the lowest common ancestor between the nodes. Let’s take an example tree- For the...

4 minutes read.

Find the nth node from the end of a Linked List

Find the nth node from the end of a Linked List In this problem, we have given a singly linked list and a number 'n,' and we need to find the...

3 minutes read.

Queue operations in Data Structure

Queue - Queue is a linear data structure or first in first out data structure means the first element added in the queue will be removed first and the last...

7 minutes read.

FLEX (Fast Lexical Analyzer Generator)

FLEX stands for Fast Lexical Analyzer Generator. Around 1987, Vern Paxson created Flex in C with a great deal of input and inspiration from Van Jacobson. Van Jacobson's approach is...

3 minutes read.

Linked List Representation of Binary Tree

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. The word binary itself represents its meaning; we know that...

4 minutes read.

Applications of trees in data structures

Data structures Storage used to organize and store data is known as the data structure. It is a method of managing computerized data to translate or retrieve it more efficiently. A...

7 minutes read.

Top view of binary tree

We know that a binary tree is a kind of tree that helps us organize our tree and that it is a kind of non-linear info structure that at least...

4 minutes read.