Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding words in a matrix in JavaScript
We need to write a JavaScript function that takes a 2D character matrix and a string, then determines if the string can be formed by connecting adjacent characters in the matrix without reusing any position.
The function searches for a path through the matrix where each character in the target string appears in sequence through adjacent cells (up, down, left, right). Each cell can only be used once per word search.
Problem Example
Given this matrix and target string:
const arr = [
['s', 'd', 'k', 'e'],
['j', 'm', 'o', 'w'],
['y', 'n', 'l']
];
const str = 'don';
console.log("Matrix:");
console.log(arr);
console.log("Target word:", str);
Matrix: [ [ 's', 'd', 'k', 'e' ], [ 'j', 'm', 'o', 'w' ], [ 'y', 'n', 'l' ] ] Target word: don
Algorithm Implementation
The solution uses backtracking with depth-first search to explore all possible paths:
const arr = [
['s', 'd', 'k', 'e'],
['j', 'm', 'o', 'w'],
['y', 'n', 'l']
];
const containsWord = (matrix = [], word = '') => {
if (matrix.length === 0 || word.length === 0) {
return false;
}
const height = matrix.length;
const width = matrix[0].length;
// Four directions: up, right, down, left
const directions = [[-1, 0], [0, 1], [1, 0], [0, -1]];
const searchWord = (row, col, index) => {
// Check if current character matches
if (matrix[row][col] !== word[index]) {
return false;
}
// Found complete word
if (index === word.length - 1) {
return true;
}
// Mark current cell as visited
const originalChar = matrix[row][col];
matrix[row][col] = '*';
// Try all four directions
for (const [deltaRow, deltaCol] of directions) {
const newRow = row + deltaRow;
const newCol = col + deltaCol;
// Check bounds and search recursively
if (newRow >= 0 && newRow < height &&
newCol >= 0 && newCol < width) {
if (searchWord(newRow, newCol, index + 1)) {
matrix[row][col] = originalChar; // restore
return true;
}
}
}
// Backtrack: restore original character
matrix[row][col] = originalChar;
return false;
};
// Try starting from each cell
for (let i = 0; i < height; i++) {
for (let j = 0; j < width; j++) {
if (searchWord(i, j, 0)) {
return true;
}
}
}
return false;
};
// Test cases
console.log("Searching for 'don':", containsWord(arr, 'don'));
console.log("Searching for 'dome':", containsWord(arr, 'dome'));
console.log("Searching for 'sk':", containsWord(arr, 'sk'));
Searching for 'don': false Searching for 'dome': true Searching for 'sk': true
How It Works
The algorithm works in these steps:
- Iterate through matrix: Start search from each cell position
- Character matching: Check if current cell matches the target character
- Mark visited: Temporarily mark cell as visited using '*'
- Explore neighbors: Recursively search adjacent cells (up, down, left, right)
- Backtrack: Restore original character if path doesn't lead to solution
Visual Example
Conclusion
This backtracking algorithm efficiently searches for words in a 2D matrix by exploring all possible paths while preventing cell reuse. The technique is commonly used in word search games and grid-based puzzles.
