×

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

Insertion sort

Insertion sort is a simple sorting technique. It is best suited for small data sets, but it does not suitable for large data sets. In this technique, we pick an...

4 minutes read.

Big O Notations

What is Big O Notation, and why is it important? "Big O notation is a mathematical notation that depicts a function's limiting behaviour when the input tends towards a certain value...

10 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.

How to get Better in Data Structures and Algorithms?

Introduction Data structures and algorithms are fundamental computer science concepts that store, organize, and process data efficiently. By understanding different data structures and algorithms and using them effectively, you can become...

19 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.

Extended Binary Tree

A form of binary tree known as an extended binary tree replaces all of the original tree's null subtrees with special nodes known as external nodes, while the remaining nodes...

4 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.

Heap Data Structure

In this article, we will learn in detail about Heap (Min heap and Max heap). Before going to the main topics, let’s have a look at what is complete binary...

19 minutes read.

Radix Sort

Radix Sort: The radix sort is a non-comparative integer sorting algorithm that sorts the elements by grouping the individual digits of the same location. It shares the same significant position...

4 minutes read.

Deletion Operation of the binary search tree in C++ language

A typical binary search tree implements some order to carry out the arrangements. As the name suggests, each parent node should have at most two children. The main rule in...

4 minutes read.

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

6 minutes read.

Linear vs Binary Search: Data Structure

Difference Between Linear and Binary Search What is Linear Search? A linear search also referred as a sequential search. It is a way to find an element within a list and it...

3 minutes read.

Primitive Data Structure in C

The data structure is a logical or mathematical model for organizing and structuring the main memory or elements. We can classify the data structures in two ways one is primitive, and...

10 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Flatten Binary Tree to a linked list

Implementation In this section, we will see the implementation of the binary Tree and its conversion into linked lists. let us proceed: - // Writing a C++ program that will convert a...

4 minutes read.

Left View of Binary Tree

Implementation // creating a C++ program to print the Left view of the binary tree. #include <bits/stdc++.h> using namespace std; struct Nod { int record; struct Nod *Lft, *Rt; }; // creating a utility function that will eventually help...

4 minutes read.

Rotate a Singly Linked List

Rotate a Singly Linked List This article will explain how we can rotate the singly linked list. Here we have given a singly linked list, and we need to rotate this...

4 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

Properties of Binary Tree

Trees are maybe of the most significant datum structures. They are used to store and figure out data. A binarytree is a tree data structure made from nodes, all of which has...

3 minutes read.

Structure and Union Data Structure

The array is used for the same type of data, but if we want to store a mixed type of data in a group, then the array cannot be used. The Structure...

4 minutes read.