JavaScript Program to Search a Word in a 2D Grid of Characters
Last Updated :
09 Jul, 2024
In this article, we will solve a problem in which you are given a grid, with characters arranged in a two-layout(2D). You need to check whether a given word is present 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.
Examples:
Input:
characterGrid = [ ['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S'],
['G', 'E', 'E', 'K', 'S', 'Q', 'U', 'I', 'Z', 'G', 'E', 'E', 'K'],
['I', 'D', 'E', 'Q', 'A', 'P', 'R', 'A', 'C', 'T', 'I', 'C', 'E']];
word = "GEEKS"
Output:
pattern found at 0, 0
pattern found at 0, 8
pattern found at 1, 0
Approach: Using Nested Loops
- In this approach, we are considering all eight possible directions in a 2D grid that is Horizontally Left, Horizontally Right, Vertically Up, Vertically Down, and 4 Diagonal directions.
- It defines the grid's dimensions in the form of numbers of rows and columns and arrays for direction (dx and dy).
- The 'searchWord" function checks if the given word matches when starting from a specific grid position and moving in each of the eight directions.
- The
findPattern
the function scans the entire grid, considering each cell as a potential starting point for the word search. - When you run the code with a provided character grid, it looks for "GEEKS" and "EEE" in the grid and prints the coordinates where these words are found.
Example:
JavaScript
// JavaScript program to search
// for a word in a 2D grid
// Define the number of rows
// and columns in the given grid
let numRows, numCols;
// Define arrays for
// searching in all 8 directions
let dx = [-1, -1, -1, 0, 0, 1, 1, 1];
let dy = [-1, 0, 1, -1, 1, -1, 0, 1];
// This function searches for a word in all
// 8 directions from a
// starting point (r, c) in the grid
function searchWord(grid, r, c, word) {
// If the first character of the word
// doesn't match with the
// starting point in the grid
if (grid[r] !== word[0])
return false;
let wordLength = word.length;
let directionIndex = 0;
// Search for the word in all 8 directions
// starting from (r, c)
while (directionIndex < 8) {
// Initialize the starting point
// for the current direction
let k, currentRow = r + dx[directionIndex];
let currentCol = c + dy[directionIndex];
// The first character is already
// checked, match the remaining characters
for (k = 1; k < wordLength; k++) {
// If out of bounds, break
if (currentRow >= numRows || currentRow < 0 ||
currentCol >= numCols || currentCol < 0)
break;
// If not matched, break
if (grid[currentRow][currentCol] !== word[k])
break;
// Move in a particular direction
currentRow += dx[directionIndex];
currentCol += dy[directionIndex];
}
// If all characters matched, the value of k must
// be equal to the length of the word
if (k === wordLength)
return true;
directionIndex++;
}
return false;
}
// Search for the given word in a given
// matrix in all 8 directions
function findPattern(grid, targetWord) {
// Consider every point as a
// starting point and search for the given word
for (let r = 0; r < numRows; r++) {
for (let c = 0; c < numCols; c++) {
if (searchWord(grid, r, c, targetWord))
console.log("Pattern found at " + r + ", " + c);
}
}
}
// Driver code
numRows = 3;
numCols = 13;
let characterGrid = [
['G', 'E', 'E', 'K', 'S', 'F', 'O',
'R', 'G', 'E', 'E', 'K', 'S'],
['G', 'E', 'E', 'K', 'S', 'Q', 'U', 'I', 'Z',
'G', 'E', 'E', 'K'],
['I', 'D', 'E', 'Q', 'A', 'P', 'R', 'A', 'C',
'T', 'I', 'C', 'E']
];
findPattern(characterGrid, "GEEKS");
findPattern(characterGrid, "EEE");
OutputPattern found at 0, 0
Pattern found at 0, 8
Pattern found at 1, 0
Pattern found at 0, 2
Pattern found at 0, 10
Pattern found at 2, 2
Pattern found at 2, 12
Time complexity: O(N^2 * M), where N is the number of rows, and M is the number of columns in the grid.
Space complexity: O(1), as the code uses a fixed amount of additional memory regardless of the grid's size.
Depth-First Search (DFS)
Using Depth-First Search (DFS) to search a word in a 2D grid involves recursively exploring each cell's neighbors (up, down, left, right) to match the word's characters, marking cells as visited to avoid revisits, and backtracking if a path doesn't lead to a solution.
Example: In this example The exist function uses DFS to search for the given word in a 2D board of characters. It marks visited cells, exploring adjacent ones until the word is found. The example correctly verifies the existence of "ABCCED" in the board, returning true.
JavaScript
function exist(board, word) {
const rows = board.length;
const cols = board[0].length;
const dfs = (i, j, k) => {
if (k === word.length) return true;
if (i < 0 || j < 0 || i >= rows || j >= cols || board[i][j] !== word[k]) return false;
const temp = board[i][j];
board[i][j] = '#'; // mark as visited
const found = dfs(i + 1, j, k + 1) ||
dfs(i - 1, j, k + 1) ||
dfs(i, j + 1, k + 1) ||
dfs(i, j - 1, k + 1);
board[i][j] = temp; // unmark
return found;
};
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (dfs(i, j, 0)) return true;
}
}
return false;
}
const board = [
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
];
const word = "ABCCED";
console.log(exist(board, word));
Approach: Using Trie Data Structure
In this approach, we use a Trie (prefix tree) data structure to store all the words that need to be searched in the grid. This allows for efficient prefix-based searching. We will build a Trie from the given word and then use backtracking to search for the word in the grid, leveraging the Trie to quickly prune invalid paths.
Example: This example demonstrates the use of the Trie data structure for the word search problem in a 2D grid.
JavaScript
class TrieNode {
constructor() {
this.children = {};
this.isEndOfWord = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let node = this.root;
for (let char of word) {
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.isEndOfWord = true;
}
search(word) {
let node = this.root;
for (let char of word) {
if (!node.children[char]) {
return null;
}
node = node.children[char];
}
return node;
}
}
function findWords(board, words) {
const result = [];
const trie = new Trie();
for (let word of words) {
trie.insert(word);
}
const directions = [
[-1, 0], [1, 0], [0, -1], [0, 1],
[-1, -1], [-1, 1], [1, -1], [1, 1]
];
function backtrack(row, col, node, path) {
if (node.isEndOfWord) {
result.push(path.join(''));
node.isEndOfWord = false; // Avoid duplicate entries
}
if (row < 0 || col < 0 || row >= board.length || col >= board[0].length || board[row][col] === '#' || !node.children[board[row][col]]) {
return;
}
const char = board[row][col];
board[row][col] = '#'; // Mark the cell as visited
path.push(char);
for (let [dx, dy] of directions) {
backtrack(row + dx, col + dy, node.children[char], path);
}
board[row][col] = char; // Unmark the cell
path.pop();
}
for (let row = 0; row < board.length; row++) {
for (let col = 0; col < board[0].length; col++) {
if (trie.root.children[board[row][col]]) {
backtrack(row, col, trie.root, []);
}
}
}
return result;
}
// Test case
const characterGrid = [
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S'],
['G', 'E', 'E', 'K', 'S', 'Q', 'U', 'I', 'Z', 'G', 'E', 'E', 'K'],
['I', 'D', 'E', 'Q', 'A', 'P', 'R', 'A', 'C', 'T', 'I', 'C', 'E']
];
const word = "GEEKS";
console.log(findWords(characterGrid, [word])); // Output: ["GEEKS"]
Similar Reads
JavaScript Program to Check if a Character is Vowel or Not
In this article, we will check if the input character is a vowel or not using JavaScript. Vowel characters are âaâ, âeâ, âiâ, âoâ, and âuâ. All other characters are not vowels. Examples: Input : 'u'Output : TrueExplanation: 'u' is among the vowel characters family (a,e,i,o,u).Input : 'b'Output : Fal
4 min read
JavaScript Program to Find Missing Characters to Make a String Pangram
We have given an input string and we need to find all the characters that are missing from the input string. We have to print all the output in the alphabetic order using JavaScript language. Below we have added the examples for better understanding. Examples: Input : welcome to geeksforgeeksOutput
7 min read
JavaScript Program to Print the First Letter of Each Word
Printing the first letter of each word involves extracting the initial character from every word in a given string, typically accomplished by splitting the string into words and selecting the first character from each resulting word. Examples of Printing the First Letter of Each Word Table of Conten
3 min read
JavaScript Program to Print Character Pattern
Printing a character pattern involves generating and displaying a structured arrangement of characters, often in a specific geometric shape such as a triangle or square. This process typically includes using loops to systematically place characters in rows and columns based on given rules. Here are
3 min read
JavaScript Program to Print Continuous Character Pattern
A program to print a continuous character pattern generates a series of characters in a structured arrangement, typically forming shapes or designs. This pattern may involve repetition, alternation, or progression of characters, creating visually appealing outputs. The program iteratively prints cha
3 min read
JavaScript Program to Match Single Character with Multiple Possibilities
In this article, we will write programs to check all possible matching in JavaScript. We will check the occurrence of characters individually in the given string or sequence. In this article, we will check the occurrence of vowels in the given string. Table of Content Using JavaScript RegExp test()
3 min read
JavaScript Program to Find all Strings that Match Specific Pattern in a Dictionary
Finding all strings in a dictionary that match a specific pattern in JavaScript involves searching for words that follow a particular structure or format within a given dictionary. The pattern can include placeholders for characters, allowing flexibility in the search. In this article, we will explo
7 min read
JavaScript Program to Print the Pattern G
This program aims to print the pattern 'G' using asterisks (*) in the console output. The pattern 'G' consists of several horizontal and vertical lines arranged to form the uppercase letter 'G'. It requires careful positioning of asterisks to represent the shape accurately. Below are the methods to
3 min read
JavaScript Program to Print all Palindromic Paths from Top Left to Bottom Right in a Matrix
We are given a matrix containing only lower-case alphabetical characters. The task is to print all the palindromic paths present in the given matrix. A path is a sequence of cells starting from the top-left cell and ending at the bottom-right cell. We are allowed to move only to the right and down f
4 min read
JavaScript Program to find Lexicographically next String
In this article, we are going to learn how can we find the Lexicographically next string. Lexicographically next string refers to finding the string that follows a given string in a dictionary or alphabetical order. Examples: Input : testOutput : tesuExplanation : The last character 't' is changed t
3 min read