Validating a boggle word using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

A Boggle board is a 2D array of individual characters, e.g. −

const board = [
   ["I","L","A","W"],
   ["B","N","G","E"],
   ["I","U","A","O"],
   ["A","S","R","L"]
];

We are required to write a JavaScript function that takes in boggle board and a string and checks whether that string is a valid guess in the boggle board or not. Valid guesses are strings which can be formed by connecting adjacent cells (horizontally, vertically, or diagonally) without reusing any previously used cells.

For example, in the above board "LINGO", and "ILNBIA" would all be valid guesses, while "BUNGIE" and "SINUS" would not.

Example

Following is the code −

 Live Demo

const board = [
   ["I","L","A","W"],
   ["B","N","G","E"],
   ["I","U","A","O"],
   ["A","S","R","L"]
];
const guess = 'BINGO';
const checkWord = (board = [], guess = '') => {
   const numRows = board.length;
   const numCols = board[0].length;
   let queue = board.reduce((acc, row, i) => {
      row.forEach((x, j) => {
         if (x === guess[0]) {
            acc.push ( { pos: {r: i, c: j} , nextIndex: 1, path: [numCols*i + j ] } );
         }
      });
      return acc;
   }, []);
   let exploreWord = (obj, queue) => {
      let allMoves = [ {r: obj.pos.r - 1, c: obj.pos.c },
      {r: obj.pos.r + 1, c: obj.pos.c },
      {r: obj.pos.r, c: obj.pos.c - 1 },
      {r: obj.pos.r, c: obj.pos.c + 1 },
      {r: obj.pos.r - 1, c: obj.pos.c - 1 },
      {r: obj.pos.r - 1, c: obj.pos.c + 1 },
      {r: obj.pos.r + 1, c: obj.pos.c - 1 },
      {r: obj.pos.r + 1, c: obj.pos.c + 1 }];
      allMoves.forEach((o) => {
         let index = numCols * o.r + o.c;
         if (o.r >= 0 && o.r < numRows && o.c >= 0 && o.c < numCols) {
            if (board[o.r][o.c] === guess[obj.nextIndex] && !obj.path.includes(index)) {
               let cloneObj = JSON.parse(JSON.stringify(obj));
               cloneObj.pos = { r: o.r, c: o.c };
               cloneObj.nextIndex += 1;
               cloneObj.path.push(index);
               queue.push(cloneObj);
            }
         }
      });
   };
   while (queue.length > 0) {
      let obj = queue.shift();
      if (obj.nextIndex === guess.length) {
         return true;
      }
      exploreWord(obj, queue);
   }
   return false;
};
console.log(checkWord(board, guess));

Code Explanation

The steps we took are −

  • We scan the 2d array to find the occurrence of the first letter

  • Then we push the { position, index } into queue, while the queue is not empty, we pop the first object out

  • Then we look for all directions. if the letter in the cell matches the letter in word and cell is not reused, we update {position, index} and append to queue otherwise, we discard the object and we stop when a match is found or all no match.

Output

true
raja
Published on 19-Apr-2021 10:47:38
Advertisements