Today I have solved the problem in javascript
You are given an N by N matrix of random letters and a dictionary of words. Find the maximum number of words that can be packed on the board from the given dictionary.
A word is considered to be able to be packed on the board if:
It can be found in the dictionary
It can be constructed from untaken letters by other words found so far on the board
The letters are adjacent to each other (vertically and horizontally, not diagonally).
Each tile can be visited only once by any word.
For example, given the following dictionary:
{ 'eat', 'rain', 'in', 'rat' }
and matrix:
[['e', 'a', 'n'],
['t', 't', 'i'],
['a', 'r', 'a']]
Your function should return 3, since we can make the words 'eat', 'in', and 'rat' without them touching each other. We could have alternatively made 'eat' and 'rain', but that would be incorrect since that's only 2 words.
const dictionary = ['eat', 'rain', 'in', 'rat'];
const matrix = [
['e', 'a', 'n'],
['t', 't', 'i'],
['a', 'r', 'a']
];
function maxWords(matrix, dictionary) {
const rows = matrix.length;
const cols = matrix[0].length;
const visited = Array.from({ length: rows }, () => Array(cols).fill(false));
function canFormWord(word, row, col, index) {
if (index === word.length) {
return true;
}
if (
row < 0 ||
row >= rows ||
col < 0 ||
col >= cols ||
visited[row][col] ||
matrix[row][col] !== word[index]
) {
return false;
}
visited[row][col] = true;
const found =
canFormWord(word, row + 1, col, index + 1) ||
canFormWord(word, row - 1, col, index + 1) ||
canFormWord(word, row, col + 1, index + 1) ||
canFormWord(word, row, col - 1, index + 1);
visited[row][col] = false;
return found;
}
function countWordsFromMatrix(word) {
let count = 0;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (!visited[i][j] && canFormWord(word, i, j, 0)) {
count++;
}
}
}
return count;
}
let maxWordCount = 0;
for (const word of dictionary) {
const wordCount = countWordsFromMatrix(word);
maxWordCount = Math.max(maxWordCount, wordCount);
}
return maxWordCount;
}
const result = maxWords(matrix, dictionary);
console.log(result);
Output:
1
Comments
Post a Comment