No es el mas eficiente pero lo logre en JS
const ADJACENT_MARTIX = [
[0, 1], [0, -1], //x
[1, 0], [-1, 0], //y
[1, 1], [-1, -1], //xy
];
const CAFE_BOARD = [
['A', 'C', 'L', 'C'],
['F', 'A', 'A', 'I'],
['I', 'F', 'E', 'U'],
];
const duplicateBoard = (board) => board.map((row) => row.map((col) => col));
const isAdjactedWord = (board, word, x, y, index) => {
return ADJACENT_MARTIX.filter((adj) => {
const adjX = x + adj[0];
const adjY = y + adj[1];
if (
board[adjX] != undefined &&
board[adjX][adjY] != undefined &&
board[adjX][adjY] === word[index]
) {
board[adjX][adjY] = '';
return true;
}
return false;
});
}
console.assert(isAdjactedWord(duplicateBoard(CAFE_BOARD), 'CAFE',0,1,1).length==3, 'Adjacent matrix length')
console.assert(isAdjactedWord(duplicateBoard(CAFE_BOARD), 'CAFE',1,1,2).length==2, 'Adjacent matrix length')
console.assert(isAdjactedWord(duplicateBoard(CAFE_BOARD), 'CAFE',2,1,3).length==1, 'Adjacent matrix length')
const isWord = (board, word, x, y) => {
let index =1;
const auxBard = board.map((row) => row.map((col) => col));
let adjacent = isAdjactedWord(auxBard, word, x, y, 1);
while (adjacent.length > 0) {
index++;
if (index === word.length) return true;
adjacent= adjacent.map((adj) =>
{
point = [adj[0]+x, adj[1]+y];
result =isAdjactedWord(auxBard, word, adj[0]+x, adj[1]+y, index);
result = result.map((adj) =>{
return [adj[0]+point[0], adj[1]+point[1]]
})
return result;
});
adjacent=adjacent.reduce((acc, cur) => {
if (cur.length > 0) {
acc.push(...cur)
}
return acc
}, [])
if (index === word.length) return true;
};
return false
}
console.assert(isWord(duplicateBoard(CAFE_BOARD), 'CAFE',0,1)==true, 'Is word inside bard')
function searchWord(board, word) {
word = word.toUpperCase();
if (word.length === 0 || board.length == 0) return false;
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[i].length; j++) {
if (board[i][j] === word[0] && isWord(board, word, i, j)) {
return true;
}
}
}
return false;
}
console.assert(searchWord([], "") === false, 'empty board and word');
console.assert(searchWord(CAFE_BOARD, "CAFE") === true, 'Search Cafe');
¿Quieres ver más aportes, preguntas y respuestas de la comunidad?