Untitled
unknown
javascript
7 months ago
1.5 kB
2
Indexable
Never
function countWordsInMatrix(matrix, words) { const numRows = matrix.length; const numCols = matrix[0].length; function generatePaths(word) { const paths = []; for (let i = 0; i <= word.length; i++) { const part1 = word.substring(0, i); const part2 = word.substring(i).split('').reverse().join(''); paths.push(part1 + part2, part2 + part1); } return paths; } function isWordInMatrix(word) { for (let row = 0; row < numRows; row++) { for (let col = 0; col < numCols; col++) { directionLoop: for (const [dx, dy] of [[0, 1], [1, 0]]) { for (let reverse = 0; reverse < 2; reverse++) { let x = row, y = col; for (let i = 0; i < word.length; i++) { if (x < 0 || x >= numRows || y < 0 || y >= numCols || matrix[x][y] !== word[i]) { continue directionLoop; } x += dx; y += dy; if (reverse === 1 && i === Math.floor(word.length / 2) - 1) { [x, y] = [row + dy * (word.length - 1), col + dx * (word.length - 1)]; [dx, dy] = [dy, dx]; } } return true; } } } } return false; } let count = 0; words.forEach(word => { const paths = generatePaths(word); for (const path of paths) { if (isWordInMatrix(path)) { count++; break; } } }); return count; }
Leave a Comment